背景
主要介绍和整理ElasticSearch 常用的API
环境
SpringBoot2.1+Maven
Maven依赖
<dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> </dependency>
索引结构
@Data @Document(indexName = "text-audit", type = "text_audit_type", shards = 1, replicas = 0, createIndex = false) public class TextModerationEntity { @Id private Long dbId; //.....其他省略 }
索引Mapper
public interface TextModerationRepository extends ElasticsearchRepository<TextModerationEntity,Long> { }
API
查询
1.分页搜索
@Autowired private IMTextModerationRepository imTextMdrRepository; BoolQueryBuilder builder = QueryBuilders.boolQuery(); //......省略其他查询条件 NativeSearchQuery queryBuilder = new NativeSearchQueryBuilder() .withQuery(builder) .withPageable(PageRequest.of(当前页码 - 1, 每页条数) .withSort(SortBuilders.fieldSort("xxxx").order(SortOrder.DESC)) .build(); Page<IMTextModerationEntity> pageResult = imTextMdrRepository.search(queryBuilder);
2.根据ID查询
Optional<IMTextModerationEntity> optional = imTextMdrRepository.findById(dbId);
3.分页查询(根据其他查询条件查询)
@Autowired private ElasticsearchTemplate elasticsearchTemplate; NativeSearchQuery queryBuilder = new NativeSearchQueryBuilder() .withQuery(builder) .withPageable(PageRequest.of(当前页码 - 1, 每页条数)) .build(); Page<IMTextModerationEntity> page = elasticsearchTemplate.queryForPage(queryBuilder, IMTextModerationEntity.class);
4.列表查询
@Autowired private ElasticsearchTemplate elasticsearchTemplate; NativeSearchQuery queryBuilder = new NativeSearchQueryBuilder() .withQuery(builder) .build();
List<ImageModerationEntity> entityList = elasticsearchTemplate.queryForList(queryBuilder, ImageModerationEntity.class);
新增
@Autowired private IMTextModerationRepository imTextMdrRepository; IMTextModerationEntity entity = new IMTextModerationEntity(); ....... imTextMdrRepository.save(entity);
更新
1.根据文档ID去更新
@Autowired private ElasticsearchTemplate elasticsearchTemplate; UpdateRequest updateRequest = new UpdateRequest(); Map<String, Object> params = Maps.newHashMap(); params.put("属性名", "属性值"); updateRequest.doc(params); UpdateQuery updateQuery = new UpdateQueryBuilder() .withId(String.valueOf(dbId)) .withClass(ImageModerationEntity.class) .withUpdateRequest(updateRequest) .build(); UpdateResponse update = elasticsearchTemplate.update(updateQuery);
2.根据其他查询条件去更新(相当于updateByQuery)
@Autowired private ElasticsearchTemplate elasticsearchTemplate; Client client = elasticsearchTemplate.getClient(); UpdateByQueryRequestBuilder builder = UpdateByQueryAction.INSTANCE.newRequestBuilder(client); builder.source("索引名/索引别名") .filter(QueryBuilders.termQuery("属性名", "属性值")) .script(new Script("ctx._source.属性名=属性值")); BulkByScrollResponse response = builder.get(); long count = response.getUpdated();
删除
//TODO
标签:JAVA,Autowired,builder,queryBuilder,private,API,ElasticSearch,elasticsearchTempl From: https://www.cnblogs.com/july-sunny/p/16640731.html