Java ‘Elasticsearch‘ 操作

依赖


    org.springframework.boot
    spring-boot-starter-data-elasticsearch
    2.3.12.RELEASE

配置

spring:
  elasticsearch:
    uris: http://192.168.0.226:9200

对象

@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;

添加索引操作

elasticsearchRestTemplate.indexOps(IndexCoordinates.of("indexname")).create();

IndexCoordinates可以给多个索引

删除索引

elasticsearchRestTemplate.indexOps(IndexCoordinates.of("indexname")).delete();

添加操作

IndexQuery indexQuery = new IndexQueryBuilder()
        .withId(productId)
                .withObject(product4ES)
                        .build();
elasticsearchRestTemplate.index(indexQuery, IndexCoordinates.of("products"));

查询操作

这个类是封装查询数据的

NativeSearchQuery query = new NativeSearchQueryBuilder()

要查询的字段

.withQuery(multiMatchQuery(keyword, "productName", "productSkuName"))

分页由于里面比尔帮你做好了就不要套用公式了

.withPageable(PageRequest.of(pageNum - 1, limit))

这里是高亮显示,用的是可变参数

.withHighlightFields(new HighlightBuilder.Field("productName").preTags(""), new HighlightBuilder.Field("productSkuName").preTags(""))

这里是构建

.build();

elasticsearchRestTemplate.search调用这个方法
search(封装的查询调教, 里面装的类型自动的, IndexCoordinates.of("要差的索引"))
SearchHits得到这个
search.getTotalHits();获取查询到的count

product4ES是我自己创建的然后装得到index

获取搜索的结果

List> searchHits = search.getSearchHits();
创建一个等等用
List list = new ArrayList<>();
for (SearchHit hit : searchHits) {
获取返回的对象用什么对象装的什么对象拿自动的
    Product4ES product4ES = hit.getContent();
获取高亮map对象多个高亮map就有多个值
    Map> highlightFields = hit.getHighlightFields();
获取叫下面这个名字的字段的高亮文本这里可能一段文字多个高亮
    List productName = highlightFields.get("productName");
    if (!productName.isEmpty()) {
拿到第一个高亮,并设置
        product4ES.setProductName(productName.get(0));
    }
设置到对象
    list.add(product4ES);
}

计算总页数

int pageCount = ((int) (count % limit == 0 ? count / limit : count / limit + 1));

你可能感兴趣的:(java,elasticsearch,开发语言)