ElasticSearch(2)使用篇
一、创建对象映射 ①创建ElasticSearch中对象 不参与索引的可以加上 "index": false, "doc_values": false PUT article { "mappings": { "properties": { "id":{ "type": "long", "index": false, "doc_values": false }, "title":{ "type": "text", "analyzer": "ik_smart" }, "createTime":{ "type": "date", "format": "yyyy-MM-dd HH:mm:ss" }, "images":{ "type": "keyword", "index": false, "doc_values": false } } } } ②java对象映射 注意LocalDateTime的处理。 @Data public class ArticleEsModel { /** * id */ private Long id; /** * 标题 */ private String title; /** * 时间 */ @Field(type = FieldType.Date,format = DateFormat.basic_date_time_no_millis,pattern = "yyyy-MM-dd HH:mm:ss") @JsonSerialize(using = LocalDateTimeSerializer.class) @JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonFormat(shape = JsonFormat.Shape.STRING,timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime; /** * 图片 */ private List<String> images; } 二、批量插入 import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.core.BulkRequest; import co.elastic.clients.elasticsearch.core.BulkResponse; import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem; import com.vanky.community.api.search.to.ArticleEsModel; import com.vanky.community.search.constant.EsContent; import com.vanky.community.search.service.ArticleSearchService; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @author vanky */ @Slf4j @Service public class ArticleSearchServiceImpl implements ArticleSearchService { @Resource private ElasticsearchClient elasticsearchClient; @Override public boolean saveArticleBatch(List<ArticleEsModel> articleEsModels) throws IOException { BulkRequest.Builder br = new BulkRequest.Builder(); for (ArticleEsModel model : articleEsModels) { br.operations(op -> op .index(idx -> idx .index(EsContent.ARTICLE_INDEX) .id(model.getId().toString()) .document(model) ) ); } //执行操作,并返回响应结果 BulkResponse bulkResponse = elasticsearchClient.bulk(br.build()); //处理错误 if(bulkResponse.errors()){ List<String> collect = Arrays.stream(bulkResponse.items().toArray(new BulkResponseItem[0])) .map(item -> item.id()) .collect(Collectors.toList()); log.error("文章保存到es出错:{}", collect); return false; } return true; } } 三、查询 ElasticSearch —- DSL查询语句 ...