springboo整合elasticSearch8 java client api

这篇具有很好参考价值的文章主要介绍了springboo整合elasticSearch8 java client api。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

官方文档: https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/connecting.html

依赖

gradle

dependencies {
    implementation 'co.elastic.clients:elasticsearch-java:8.1.2'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.2'
    implementation 'jakarta.json:jakarta.json-api:2.0.1'
}

maven

<project>
  <dependencies>

    <dependency>
      <groupId>co.elastic.clients</groupId>
      <artifactId>elasticsearch-java</artifactId>
      <version>8.1.2</version>
    </dependency>

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

es配置类

package com.demo.devops.document.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
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.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ES配置
 */
@Configuration
public class ElasticSearchConfig {

    @Value("${es.hostname:10.129.129.1}")
    private String hostname;
    @Value("${es.port:9200}")
    private int port;
    @Value("${es.username:elastic}")
    private String username;
    @Value("${es.password:123456}")
    private String password;

    @Bean
    public ElasticsearchClient esRestClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        // Create the low-level client
        RestClient restClient = RestClient.builder(new HttpHost(hostname, port)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        // And create the API client
        return new ElasticsearchClient(transport);
    }
}


若无密码,可以使用下面方式:

// Create the low-level client
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
// And create the API client
ElasticsearchClient client = new ElasticsearchClient(transport);

操作

创建索引

使用es自动设置的mapping

    @Autowired
    private ElasticsearchClient elasticsearchClient;
    ----
	//创建索引
	CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("newapi"));

设置mappings

    @Autowired
    private ElasticsearchClient elasticsearchClient;
    
	public void createDocIndex() throws IOException {
        log.info("开始新建ES索引");
        Map<String, Property> documentMap = new HashMap<>();
        documentMap.put("title", Property.of(property ->
                        property.text(TextProperty.of(p ->
                                        p.index(true)
                                                .analyzer("ik_max_word")
                                )
                        )
                )
        );
        documentMap.put("id", Property.of(property ->
                        property.long_(LongNumberProperty.of(p ->
                                        p.index(true)
                                )
                        )
                )
        );

        documentMap.put("content", Property.of(property ->
                        property.text(TextProperty.of(textProperty ->
                                        textProperty.index(true)
                                                .analyzer("ik_max_word")
                                )
                        )
                )
        );
        documentMap.put("createUserId", Property.of(property ->
                        property.keyword(KeywordProperty.of(p ->
                                        p.index(true)
                                )
                        )
                )
        );

        documentMap.put("createTime", Property.of(property ->
                        property.date(DateProperty.of(p ->
                                        p.index(true)
                                )
                        )
                )
        );
        // 创建索引
        CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(c -> {
            c.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL)
                    .mappings(mappings -> mappings.properties(documentMap));
            //.aliases(SystemConstant.INDEX_DOC_ALL, aliases -> aliases.isWriteIndex(true));
            return c;
        });
        log.info("结束新建ES索引,res={}", createIndexResponse.acknowledged());
    }

删除索引

    public void deleteIndex(String index) throws IOException {
        log.info("开始删除索引,index={}", index);
        DeleteIndexResponse response = elasticsearchClient.indices().delete(d -> d.index(index));
        log.info("开始删除索引,index={},res={}", index, response.acknowledged());
    }

新建文档

Doc是自定义实体类

    @Async
    public void createDoc(Doc doc) {
        log.info("开始新增到es,docNo={}", doc.getDocNo());
        // 构建一个创建Doc的请求
        try {
            String newContent = convertContent(doc.getContent());
            doc.setContent(newContent);
            elasticsearchClient.index(x -> x.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL).document(doc));
        } catch (IOException e) {
            log.error("新增es文档异常,docNo=" + doc.getDocNo(), e);
        }
        log.info("结束新增到es,docNo={}", doc.getDocNo());
    }

批量新建文档

    /**
     * 批量新增文档到Es
     *
     * @throws IOException
     */
    public void bulkCreateDocument() throws IOException {
        log.info("开始批量新增doc到es");
        List<Doc> docList = docService.list().stream().filter(x -> !DocStateEnum.DELETED.getState().equals(x.getState())).collect(Collectors.toList());
        log.info("批量新增doc到es,查询到doc数量={}", docList.size());

        //构建一个批量操作BulkOperation的集合
        List<BulkOperation> bulkOperations = new ArrayList<>();
        //向集合添加数据
        for (Doc doc : docList) {
            bulkOperations.add(new BulkOperation.Builder().create(d -> d.document(doc).index(SystemConstant.ElasticConstants.INDEX_DOC_ALL)).build());
        }
        //使用bulk方法执行批量操作并获得响应
        BulkResponse response = elasticsearchClient.bulk(e -> e.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL).operations(bulkOperations));
        //打印结果
        log.info("新增完成,耗时={}ms", response.took());
    }

删除文档

    @Async
    public void deleteDoc(Doc doc) {
        log.info("开始删除es文档,docNo={}", doc.getDocNo());
        // 构建一个创建Doc的请求
        try {
            SearchResponse<Doc> response = elasticsearchClient.search(s -> s
                            .index(SystemConstant.ElasticConstants.INDEX_DOC_ALL)
                            .query(q -> q.term(
                                    t -> t
                                            .field(SystemConstant.ElasticConstants.FIELD_DOC_NO)
                                            .value(doc.getDocNo())
                            ))
                    , Doc.class);
            if (response.hits().total().value() == 0) {
                return;
            }
            elasticsearchClient.delete(x -> x.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL).id(response.hits().hits().get(0).id()));
        } catch (IOException e) {
            log.error("删除es文档异常,docNo=" + doc.getDocNo(), e);
        }
        log.info("结束删除es文档,docNo={}", doc.getDocNo());
    }

更新文档

    /**
     * 更新文档
     */
    @Async
    @Override
    public void updateDoc(Doc doc) {
        log.info("开始修改es文档,docNo={}", doc.getDocNo());
        try {
            SearchResponse<Doc> response = elasticsearchClient.search(s -> s
                            .index(SystemConstant.ElasticConstants.INDEX_DOC_ALL)
                            .query(q -> q.term(
                                    t -> t
                                            .field(SystemConstant.ElasticConstants.FIELD_DOC_NO)
                                            .value(doc.getDocNo())
                            ))
                    , Doc.class);
            assert response.hits().total() != null;
            if (response.hits().total().value() == 0) {
                //新增
                createDoc(doc);
            } else {
                //更新
                String newContent = convertContent(doc.getContent());
                doc.setContent(newContent);
                elasticsearchClient.update(e -> e.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL).id(response.hits().hits().get(0).id()).doc(doc), Doc.class);
            }
        } catch (IOException e) {
            log.error("更新es文档异常,docNo=" + doc.getDocNo(), e);
        }
        log.info("结束修改es文档,docNo={}", doc.getDocNo());
    }

查询一个文档

    /**
     * 根据文档docNo查询一个文档
     *
     * @param docNo
     * @return
     * @throws IOException
     */
    @Override
    public Doc searchOneDoc(Long docNo) throws IOException {
        SearchResponse<Doc> response = elasticsearchClient.search(s -> s
                        .index(SystemConstant.ElasticConstants.INDEX_DOC_ALL)
                        .query(q -> q.term(
                                t -> t
                                        .field(SystemConstant.ElasticConstants.FIELD_DOC_NO)
                                        .value(docNo)
                        ))
                , Doc.class);
        if (response.hits().total().value() == 0) {
            return null;
        }
        return response.hits().hits().get(0).source();
    }

文档检索

    /**
     * 文档检索
     *
     * @param param
     * @return
     * @throws IOException
     */
    @Override
    public PageInfo<Doc> docSearch(DocSearchParam param) throws IOException {
        // 分页查询
        SearchResponse<Doc> response = elasticsearchClient.search(s -> searchConditionBuilder(param, s)
                , Doc.class);
        log.info("检索完成,耗时={}ms,hit总数={}", response.took(), response.hits().total().value());
        List<Doc> docList = response.hits().hits().stream().map(x -> {
            Doc doc = x.source();
            if (doc == null) {
                return null;
            }
            Map<String, List<String>> highlight = x.highlight();
            List<String> titleList = highlight.get(SystemConstant.ElasticConstants.FIELD_TITLE);
            List<String> contentList = highlight.get(SystemConstant.ElasticConstants.FIELD_CONTENT);

            if (!CollectionUtils.isEmpty(titleList)) {
                doc.setTitle(titleList.get(0));
            }
            if (CollectionUtils.isEmpty(contentList)) {
                int length = doc.getContent().length();
                doc.setContent(doc.getContent().substring(0, Math.min(length, 300)).replaceAll("\n", ""));
            } else {
                doc.setContent(contentList.stream().limit(5).collect(Collectors.joining()).replaceAll("\n", ""));
            }
            return doc;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return PageInfo.pageOf(docList, Long.valueOf(response.hits().total().value()).intValue(), param.getPageSize(), param.getPageNum());
    }


 	/**
     * doc检索表达式
     *
     * @param param
     * @param s
     * @return
     */
    private SearchRequest.Builder searchConditionBuilder(DocSearchParam param, SearchRequest.Builder s) {
        SearchRequest.Builder builder = s
                .index(SystemConstant.ElasticConstants.INDEX_DOC_ALL)
                .query(q -> q
                        //.term(t -> t
                        //        .field("content")
                        //        .value(param.getKw()).
                        //)
                        .bool(b -> b.should(should -> should
                                                //.wildcard(m -> m
                                                //        .field(SystemConstant.ElasticConstants.FIELD_TITLE)
                                                //        .value("*" + param.getKw() + "*")
                                                //)
                                                //字段映射中必须使用分词器,否则查不出来
                                                //.fuzzy(f -> f
                                                //        .field(SystemConstant.ElasticConstants.FIELD_TITLE)
                                                //        .value(param.getKw())
                                                //)
                                                .match(m -> m
                                                        .field(SystemConstant.ElasticConstants.FIELD_TITLE)
                                                        .query(param.getKw())
                                                )
                                        )
                                        .should(should -> should
                                                .match(m -> m
                                                        .field(SystemConstant.ElasticConstants.FIELD_CONTENT)
                                                        .query(param.getKw())
                                                )
                                        )
                        )
                )
                //高亮
                .highlight(h -> h
                        .fields(SystemConstant.ElasticConstants.FIELD_CONTENT, f -> f
                                .preTags("<font color='red'>")
                                .postTags("</font>")
                        )
                        .fields(SystemConstant.ElasticConstants.FIELD_TITLE, f -> f
                                .preTags("<font color='red'>")
                                .postTags("</font>")
                        )
                )
                .from(param.getPageNum() * param.getPageSize() - param.getPageSize())
                .size(param.getPageSize());
		//排序字段为空,则使用默认排序
        if (StringUtils.isNotBlank(param.getOrderField())) {
            builder.sort(sort -> sort.field(f -> f
                            .field(Optional.ofNullable(param.getOrderField()).orElse(SystemConstant.ElasticConstants.FIELD_UPDATE_TIME))
                            .order(SortOrder.Desc.jsonValue().equals(param.getOrderType()) ? SortOrder.Desc : SortOrder.Asc)
                    )
            );
        }
        return builder;
    }

in语句的elastic写法-terms

比如 select * from doc where user_id in(1,2,3);

方式一:

ArrayList<String> list = new ArrayList<>();
List<FieldValue> valueList = list.stream().map(x -> FieldValue.of(x)).collect(Collectors.toList());
Query foldersQuery = TermsQuery.of(t -> t.field("userId").terms(new TermsQueryField.Builder()
        .value(folderIdValues).build()
))._toQuery();
SearchRequest.Builder builder = s.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL).query(foldersQuery);

方式二:

ArrayList<String> list = new ArrayList<>();
List<FieldValue> valueList = list.stream().map(x -> FieldValue.of(x)).collect(Collectors.toList());
SearchRequest searchRequest = SearchRequest.of(s -> s.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL).query(q ->
        q.terms(t ->
                t.field("userId")
                        .terms(new TermsQueryField.Builder()
                                .value(valueList).build()))));
SearchResponse<Doc> search = elasticsearchClient.search(searchRequest, Doc.class);

方式三:文章来源地址https://www.toymoban.com/news/detail-546357.html

ArrayList<String> list = new ArrayList<>();
List<FieldValue> valueList = list.stream().map(x -> FieldValue.of(x)).collect(Collectors.toList());
SearchResponse<Doc> response = elasticsearchClient.search(s-> s.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL).query(q ->
                q.terms(t ->
                        t.field("userId")
                                .terms(new TermsQueryField.Builder()
                                        .value(valueList).build())))
        , Doc.class);

到了这里,关于springboo整合elasticSearch8 java client api的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • java-springboot整合ElasticSearch8.2复杂查询

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

    2024年02月11日
    浏览(42)
  • Elasticsearch8.x版本中RestHighLevelClient被弃用,新版本中全新的Java客户端Elasticsearch Java API Client中常用API练习

    在Es7.15版本之后,es官方将它的高级客户端RestHighLevelClient标记为弃用状态。同时推出了全新的java API客户端Elasticsearch Java API Client,该客户端也将在Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。 Elasticsearch Java API Client支持除Vector title search API和Find structure API之外的所有

    2023年04月08日
    浏览(32)
  • SpringBoot整合ElasticSearch之Java High Level REST Client

    1 搭建SpringBoot工程 2 引入ElasticSearch相关坐标。 3 编写核心配置类 编写核心配置文件: 这里可以不写在配置,可以直接写在代码中,只是一般都是写在配置文件中 编写核心配置类 4 测试客户端对象 记得把maven的单元测试关了 注意:使用@Autowired注入RestHighLevelClient 如果报红线

    2024年02月05日
    浏览(44)
  • SpringBoot整合最新Elasticsearch Java API Client 7.16教程

        最新在学习SpringBoot整合es的一些知识,浏览了网上的一些资料,发现全都是es很久之前的版本了,其中比较流行的是Java REST Client的High Level Rest Client版本,但是官方文档的说明中,已经申明该版本即将废弃,不再进行维护了。可见:官方文档     目前官方推荐的版本是

    2023年04月24日
    浏览(29)
  • ElasticSearch8 - SpringBoot整合ElasticSearch

    springboot 整合 ES 有两种方案,ES 官方提供的 Elasticsearch Java API Client 和 spring 提供的 [Spring Data Elasticsearch](Spring Data Elasticsearch) 两种方案各有优劣 Spring:高度封装,用着舒服。缺点是更新不及时,有可能无法使用 ES 的新 API ES 官方:更新及时,灵活,缺点是太灵活了,基本是一

    2024年03月25日
    浏览(85)
  • springboot整合elasticsearch8

    1.引入maven依赖 2.application.yml添加配置 3.编写config文件 启动demo项目,通过控制台日志查看是否能够正常连接es。 4.在DemoApplicationTests编写简单测试操作es。

    2024年02月12日
    浏览(39)
  • springboot整合elasticsearch8组合条件查询

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

    2024年02月16日
    浏览(40)
  • 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日
    浏览(31)
  • 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日
    浏览(52)
  • SpringBoot3整合Elasticsearch8.x之全面保姆级教程

    安装配置 ES : https://blog.csdn.net/qq_50864152/article/details/136724528 安装配置 Kibana : https://blog.csdn.net/qq_50864152/article/details/136727707 新建项目:新建名为 web 的 SpringBoot3 项目 公共配置 介绍:一个开源的高扩展的分布式全文检索引擎,可以近乎实时的存储 和检索数据 依赖: web 模块

    2024年04月13日
    浏览(39)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包