Elasticsearch8.8.0 SpringBoot实战操作各种案例(索引操作、聚合、复杂查询、嵌套等)

这篇具有很好参考价值的文章主要介绍了Elasticsearch8.8.0 SpringBoot实战操作各种案例(索引操作、聚合、复杂查询、嵌套等)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Elasticsearch8.8.0 全网最新版教程 从入门到精通 通俗易懂

配置项目

引入依赖


        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.16</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.8.0</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
            <version>2.0.1</version>
        </dependency>

添加配置文件

application.yaml

spring:
  elasticsearch:
    rest:
      scheme: https
      host: localhost
      port: 9200
      username: elastic
      password: 123456
      crt: classpath:ca.crt

导入ca证书到项目中

从任意一个es容器中,拷贝证书到resources目录下

/usr/share/elasticsearch/config/certs/ca

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EXytUrDp-1691330960034)(media/16912196423122/16912204609393.jpg)]文章来源地址https://www.toymoban.com/news/detail-638092.html

添加配置

package com.lglbc.elasticsearch;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.TransportUtils;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;

import javax.net.ssl.SSLContext;
import java.io.IOException;

/**
 * @Description TODO
 * @Author 关注公众号 “乐哥聊编程” 领取资料和源码 
 * @Date 2023/07/14 21:04
 */
@Configuration
public class ElasticConfig {
    @Value("${spring.elasticsearch.rest.scheme}")
    private String scheme;
    @Value("${spring.elasticsearch.rest.host}")
    private String host;
    @Value("${spring.elasticsearch.rest.port}")
    private int port;
    @Value("${spring.elasticsearch.rest.crt}")
    private String crt;
    @Value("${spring.elasticsearch.rest.username}")
    private String username;
    @Value("${spring.elasticsearch.rest.password}")
    private String password;
    @Autowired
    private ResourceLoader resourceLoader;

    @Bean
    public ElasticsearchClient elasticsearchClient() throws IOException {

        SSLContext sslContext = TransportUtils
                .sslContextFromHttpCaCrt(resourceLoader.getResource(crt).getFile());
        BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
        credsProv.setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials(username, password)
        );

        RestClient restClient = RestClient
                .builder(new HttpHost(host, port, scheme))
                .setHttpClientConfigCallback(hc -> hc
                        .setSSLContext(sslContext)
                        .setDefaultCredentialsProvider(credsProv)
                )
                .build();

// Create the transport and the API client
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        return client;
    }
}

实战操作

创建mapping

    @Test
    public void testCreateMapping() throws IOException {
        PutMappingRequest mappingRequest = new PutMappingRequest.Builder().index("lglbc_java_demo")
                .properties("order_no", builder ->
                        builder.keyword(type -> type)
                ).properties("order_time", builder ->
                        builder.date(type -> type.format("yyyy-MM-dd HH:mm:ss"))
                ).properties("good_info", type -> type.nested(
                        nested -> nested
                                .properties("good_price", builder ->
                                        builder.double_(subType -> subType))
                                .properties("good_count", builder ->
                                        builder.integer(subType -> subType))
                                .properties("good_name", builder ->
                                        builder.text(subType ->
                                                subType.fields("keyword", subTypeField -> subTypeField.keyword(subSubType -> subSubType)))
                                ))
                ).properties("buyer", builder ->
                        builder.keyword(type -> type)
                ).properties("phone", builder ->
                        builder.keyword(type -> type)
                )
                .build();
        ElasticsearchIndicesClient indices = elasticsearchClient.indices();
        if (indices.exists(request -> request.index("lglbc_java_demo")).value()) {
            indices.delete(request -> request.index("lglbc_java_demo"));
        }
        indices.create(request -> request.index("lglbc_java_demo"));
        indices.putMapping(mappingRequest);
    }

创建文档

@Test
    public void testAddData() throws IOException {
        OrderInfo orderInfo = new OrderInfo("1001", new Date(), "李白", "13098762567");
        List<OrderInfo.GoodInfo> goodInfos = new ArrayList<>();
        goodInfos.add(new OrderInfo.GoodInfo("苹果笔记本", 30.5d, 30));
        goodInfos.add(new OrderInfo.GoodInfo("苹果手机", 20.5d, 10));
        orderInfo.setGoodInfo(goodInfos);
        IndexRequest<OrderInfo> request = IndexRequest.of(i -> i
                .index("lglbc_java_demo")
                .id(orderInfo.getOrderNo())
                .document(orderInfo)
        );
        OrderInfo orderInfo2 = new OrderInfo("1002", new Date(), "苏轼", "13098762367");
        List<OrderInfo.GoodInfo> goodInfos2 = new ArrayList<>();
        goodInfos2.add(new OrderInfo.GoodInfo("华为笔记本", 18.5d, 15));
        goodInfos2.add(new OrderInfo.GoodInfo("苹果手机", 20.5d, 10));
        orderInfo2.setGoodInfo(goodInfos2);
        IndexRequest<OrderInfo> request2 = IndexRequest.of(i -> i
                .index("lglbc_java_demo")
                .id(orderInfo2.getOrderNo())
                .document(orderInfo2)
        );
        elasticsearchClient.index(request);
        elasticsearchClient.index(request2);
    }

查询更新

    @Test
    public void testUpdateDataByQuery() throws IOException {
        UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i
                .index("lglbc_java_demo")
                .query(query -> query.term(term -> term.field("order_no").value("1001")))
                .script(script -> script.inline(inline -> inline.lang("painless").source("ctx._source['buyer'] = 'java 更新->乐哥聊编程'")))
        );
        elasticsearchClient.updateByQuery(request);
    }

全量更新

    @Test
    public void testUpdateData() throws IOException {
        OrderInfo orderInfo3 = new OrderInfo("1002", new Date(), "苏轼3", "13098762367");
        List<OrderInfo.GoodInfo> goodInfos3 = new ArrayList<>();
        goodInfos3.add(new OrderInfo.GoodInfo("华为笔记本", 18.5d, 15));
        goodInfos3.add(new OrderInfo.GoodInfo("苹果手机", 20.5d, 10));
        orderInfo3.setGoodInfo(goodInfos3);
        UpdateRequest request = UpdateRequest.of(i -> i
                .index("lglbc_java_demo")
                .id(orderInfo3.getOrderNo())
                .doc(orderInfo3)
        );
        elasticsearchClient.update(request, OrderInfo.class);
    }

删除数据

    @Test
    public void testDelete() throws IOException {
        DeleteRequest request = DeleteRequest.of(i -> i
                .index("lglbc_java_demo")
                .id("1002")
        );
        elasticsearchClient.delete(request);
    }

批量操作(bulk)

    @Test
    public void testBulkOperation() throws IOException {
        testCreateMapping();
        BulkRequest.Builder br = new BulkRequest.Builder();
        List<OrderInfo> orders = getOrders();
        for (OrderInfo orderInfo : orders) {
            br.operations(op -> op
                    .index(idx -> idx
                            .index("lglbc_java_demo")
                            .document(orderInfo)
                    )
            );
        }
        elasticsearchClient.bulk(br.build());
    }

基本搜索

    @Test
    public void testBaseSearch() throws IOException {
        SearchRequest request = SearchRequest.of(i -> i
                .index("lglbc_java_demo")
                .query(query -> query.term(
                        term -> term.field("order_no").value("1001")
                )));
        SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);
        List<Hit<OrderInfo>> hits = response.hits().hits();
        List<OrderInfo> orderInfos = new ArrayList<>();
        for (Hit hit : hits) {
            orderInfos.add((OrderInfo) hit.source());
        }
        System.out.println(JSONUtil.toJsonStr(orderInfos));
    }

复杂布尔搜索

    @Test
    public void testBoolSearch() throws IOException {
        SearchRequest request = SearchRequest.of(i -> i
                .index("lglbc_java_demo")
                .query(query -> query.bool(bool -> bool
                        .filter(filterQuery -> filterQuery.term(term -> term.field("buyer").value("李白")))
                        .must(must -> must.term(term -> term.field("order_no").value("1004"))))));
        SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);
        List<Hit<OrderInfo>> hits = response.hits().hits();
        List<OrderInfo> orderInfos = new ArrayList<>();
        for (Hit hit : hits) {
            orderInfos.add((OrderInfo) hit.source());
        }
        System.out.println(JSONUtil.toJsonStr(orderInfos));
    }

嵌套(nested)搜索

    @Test
    public void testNestedSearch() throws IOException {
        SearchRequest request = SearchRequest.of(i -> i
                .index("lglbc_java_demo")
                .query(query -> query.nested(nested -> nested
                        .path("good_info")
                        .query(nestedQuery -> nestedQuery.bool(
                                        bool -> bool
                                                .must(must -> must.range(range -> range.field("good_info.good_count").gte(JsonData.of("16"))))
                                                .must(must2 -> must2.range(range -> range.field("good_info.good_price").gte(JsonData.of("30"))))
                                )
                        )
                )));
        SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);
        List<Hit<OrderInfo>> hits = response.hits().hits();
        List<OrderInfo> orderInfos = new ArrayList<>();
        for (Hit hit : hits) {
            orderInfos.add((OrderInfo) hit.source());
        }
        System.out.println(JSONUtil.toJsonStr(orderInfos));
    }

分页查询

   @Test
    public void testBasePageSearch() throws IOException {
        SearchRequest request = SearchRequest.of(i -> i
                .index("lglbc_java_demo")
                .from(0)
                .size(2).query(query -> query.matchAll(matchAll -> matchAll)));
        SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);
        List<Hit<OrderInfo>> hits = response.hits().hits();
        List<OrderInfo> orderInfos = new ArrayList<>();
        for (Hit hit : hits) {
            orderInfos.add((OrderInfo) hit.source());
        }
        System.out.println(orderInfos.size());

        request = SearchRequest.of(i -> i
                .index("lglbc_java_demo")
                .from(2)
                .size(2).query(query -> query.matchAll(matchAll -> matchAll)));
        response = elasticsearchClient.search(request, OrderInfo.class);
        hits = response.hits().hits();
        orderInfos = new ArrayList<>();
        for (Hit hit : hits) {
            orderInfos.add((OrderInfo) hit.source());
        }
        System.out.println(orderInfos.size());

        request = SearchRequest.of(i -> i
                .index("lglbc_java_demo")
                .from(4)
                .size(2).query(query -> query.matchAll(matchAll -> matchAll)));
        response = elasticsearchClient.search(request, OrderInfo.class);
        hits = response.hits().hits();
        orderInfos = new ArrayList<>();
        for (Hit hit : hits) {
            orderInfos.add((OrderInfo) hit.source());
        }
        System.out.println(orderInfos.size());
    }

滚动分页查询

@Test
    public void testScrollPageSearch() throws IOException {
        String scrollId = null;
        while (true) {
            List<OrderInfo> orderInfos = new ArrayList<>();
            if (StringUtils.isBlank(scrollId)) {
                SearchRequest request = SearchRequest.of(i -> i
                        .index("lglbc_java_demo")
                        .scroll(Time.of(time -> time.time("1m")))
                        .size(2)
                        .query(query -> query.matchAll(matchAll -> matchAll)));
                SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);
                List<Hit<OrderInfo>> hits = response.hits().hits();
                for (Hit hit : hits) {
                    orderInfos.add((OrderInfo) hit.source());
                }
                scrollId = response.scrollId();
            } else {
                String finalScrollId = scrollId;
                ScrollRequest request = ScrollRequest.of(i -> i
                        .scroll(Time.of(time -> time.time("1m")))
                        .scrollId(finalScrollId));
                ScrollResponse response = elasticsearchClient.scroll(request, OrderInfo.class);
                List<Hit<OrderInfo>> hits = response.hits().hits();
                for (Hit hit : hits) {
                    orderInfos.add((OrderInfo) hit.source());
                }
                scrollId = response.scrollId();
            }
            if (CollectionUtil.isEmpty(orderInfos)) {
                break;
            }
            System.out.println(orderInfos.size());
        }
    }

After分页查询

@Test
    public void testAfterPageSearch() throws IOException {
        final List<FieldValue>[] sortValue = new List[]{new ArrayList<>()};
        while (true) {
            List<OrderInfo> orderInfos = new ArrayList<>();
            SearchRequest request = SearchRequest.of(i -> {
                SearchRequest.Builder sort1 = i
                        .index("lglbc_java_demo")
                        .size(2)
                        .sort(Lists.list(
                                SortOptions.of(sort -> sort.field(field -> field.field("order_no").order(SortOrder.Desc))))
                        );
                if (CollectionUtil.isNotEmpty(sortValue[0])) {
                    sort1.searchAfter(sortValue[0]);
                }
                return sort1
                        .query(query -> query.matchAll(matchAll -> matchAll));
            });
            SearchResponse<OrderInfo> response = elasticsearchClient.search(request, OrderInfo.class);
            List<Hit<OrderInfo>> hits = response.hits().hits();
            for (Hit hit : hits) {
                orderInfos.add((OrderInfo) hit.source());
                sortValue[0] = hit.sort();
            }
            if (CollectionUtil.isEmpty(orderInfos)) {
                break;
            }
            System.out.println(orderInfos.size());
        }

    }

词条(terms)聚合

@Test
    public void testTermsAgg() throws IOException {
        SearchRequest request = SearchRequest.of(i -> i
                .index("lglbc_java_demo")
                .query(query -> query
                        .matchAll(match->match))
                .aggregations("agg_term_buyer",agg->agg
                        .dateHistogram(dateHistogram->dateHistogram
                                .field("order_time")
                                .calendarInterval(CalendarInterval.Day))));
        SearchResponse<Void> search = elasticsearchClient.search(request, Void.class);
        Map<String, Aggregate> aggregations = search.aggregations();
        Aggregate aggregate = aggregations.get("agg_term_buyer")
                ;
        Buckets<StringTermsBucket> buckets = ((StringTermsAggregate) aggregate._get()).buckets();
        for (StringTermsBucket bucket : buckets.array()) {
            String key = bucket.key()._toJsonString();
            long l = bucket.docCount();
            System.out.println(key+":::"+l);
        }
    }

日期聚合

@Test
    public void testDateAgg() throws IOException {
        SearchRequest request = SearchRequest.of(i -> i
                .index("lglbc_java_demo")
                .query(query -> query
                        .matchAll(match->match))
                .aggregations("agg_date_buyer",agg->agg
                        .dateHistogram(dateHistogram->dateHistogram
                                .field("order_time")
                                .calendarInterval(CalendarInterval.Day))));
        SearchResponse<Void> search = elasticsearchClient.search(request, Void.class);
        Map<String, Aggregate> aggregations = search.aggregations();
        Aggregate aggregate = aggregations.get("agg_date_buyer");
        List<DateHistogramBucket> buckets = ((DateHistogramAggregate) aggregate._get()).buckets().array();
        System.out.println(aggregate);
        for (DateHistogramBucket bucket : buckets) {
            String key = bucket.keyAsString();
            long l = bucket.docCount();
            System.out.println(key+":::"+l);
        }
    }

到了这里,关于Elasticsearch8.8.0 SpringBoot实战操作各种案例(索引操作、聚合、复杂查询、嵌套等)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • ElasticSearch8 - 基本操作

    本文记录 ES 的一些基本操作,就是对官方文档的一些整理,按自己的习惯重新排版,凑合着看。官方的更详细,建议看官方的。 下文以 books 为索引名举例。 添加单个文档 (没有索引会自动创建) 不指定 id,会随机生成,如果需要指定 id,使用 POST books/_doc/id 还可以使用 put 的

    2024年04月09日
    浏览(39)
  • 【springboot-04】ElasticSearch8.7搜索

    为什么学?因为它 查询速度很快 ,而且是非关系型数据库 (NoSql) 一些增删改查已经配置好了,无需重复敲码 ElasticSearch 更新快,本篇文章将主要介绍一些常用方法。 对于 spirngboot 整合 Es 的文章很少,有些已经过时【更新太快了】  依赖:Maven 配置类:EsConfig 水果信息

    2024年02月07日
    浏览(51)
  • java(springboot)对接elasticsearch8+

    注:jackson包es只用到了databind,之所以全部引用是因为actuator用到了其他,只升级一个会 导致版本冲突 注:因为没有用springboot自身的es插件所以健康检查检测不到es状态,关闭es检测 上边创建索引是定制的加了特殊mapping,正常这样

    2024年02月16日
    浏览(44)
  • ElasticSearch8.x操作记录

    文档内容来自于尚硅谷海波老师的ElasticSearch教程课,在Kibana中的一些操作演示 以下为在文档中的相关操作记录 1.索引操作 2.文档操作 3.文档搜索 4.聚合搜索 5.索引模板 6.中文分词 7.文档评分机制 : 1, “description”: “freq, occurrences of term within document”, “details”: [] }, { “val

    2024年02月03日
    浏览(43)
  • springBoot整合ElasticSearch8.x版本

    导入依赖   dependency         groupIdcom.fasterxml.jackson.core/groupId         artifactIdjackson-databind/artifactId         version2.13.2/version   /dependency     dependency         groupIdorg.glassfish/groupId         artifactIdjakarta.json/artifactId         version2.0.1/version   /dependency           dependency  

    2023年04月21日
    浏览(43)
  • springboot整合elasticsearch8组合条件查询

    整合过程见上一篇文章 springboot整合elasticsearch8 1.es8多条件组合查询 2.使用scroll进行大数据量查询

    2024年02月16日
    浏览(54)
  • Springboot3.1+Elasticsearch8.x匹配查询

    springboot-starter3.1.0中spring-data-elasticsearch的版本为5.1.0,之前很多方法和类都找不到了。这里主要讲讲在5.1.0版本下如何使用spring data对elesticsearch8.x进行匹配查询。 第一步当然是配置依赖 在这里面,spring-boot-starter-data-elasticsearch是3.1.0的,里面的spring-data-elasticsearch是5.1.0的,服务

    2024年02月15日
    浏览(46)
  • java操作 elasticsearch8.0 doc文档<二>

    如何连接请看上一篇文章 https://blog.csdn.net/u013979493/article/details/123122242?spm=1001.2014.3001.5502 本文所有方法本人以测试正常使用,如有错误请指正,一起讨论 以下为本文所有代码 制作不易,请尊重作者的劳动成果

    2023年04月11日
    浏览(38)
  • SpringBoot3.0 整合 ElasticSearch8.5.0 及使用

    这两个版本都是目前较新的版本,本文选用的依赖是 spring-boot-starter-data-elasticsearch:3.0 ,这个新版本也是改用了es的 elasticsearch-java API,全面推荐使用Lambda语法;另外SpringData本身推出了 Repository 功能(有些类似Mybatis-Plus)的功能,也支持注解简化开发。 Docker 快速部署 单机 ela

    2024年02月11日
    浏览(65)
  • java-springboot整合ElasticSearch8.2复杂查询

    近期有大数据项目需要用到es,而又是比较新的es版本,网上也很少有8.x的java整合教程,所有写下来供各位参考。 首先 1.导包: 2.客户端连接代码EsUtilConfigClint: 一开始按照其他博主的方法,长时间连接不操作查询再次调用查询时会报错timeout,所以要设置RequestConfigCallback 3

    2024年02月11日
    浏览(53)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包