国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

springboo整合elasticSearch8 java client api

這篇具有很好參考價(jià)值的文章主要介紹了springboo整合elasticSearch8 java client api。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

官方文檔: 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);

操作

創(chuàng)建索引

使用es自動(dòng)設(shè)置的mapping

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

設(shè)置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)
                                )
                        )
                )
        );
        // 創(chuàng)建索引
        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("結(jié)束新建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是自定義實(shí)體類

    @Async
    public void createDoc(Doc doc) {
        log.info("開始新增到es,docNo={}", doc.getDocNo());
        // 構(gòu)建一個(gè)創(chuàng)建Doc的請(qǐng)求
        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("結(jié)束新增到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數(shù)量={}", docList.size());

        //構(gòu)建一個(gè)批量操作BulkOperation的集合
        List<BulkOperation> bulkOperations = new ArrayList<>();
        //向集合添加數(shù)據(jù)
        for (Doc doc : docList) {
            bulkOperations.add(new BulkOperation.Builder().create(d -> d.document(doc).index(SystemConstant.ElasticConstants.INDEX_DOC_ALL)).build());
        }
        //使用bulk方法執(zhí)行批量操作并獲得響應(yīng)
        BulkResponse response = elasticsearchClient.bulk(e -> e.index(SystemConstant.ElasticConstants.INDEX_DOC_ALL).operations(bulkOperations));
        //打印結(jié)果
        log.info("新增完成,耗時(shí)={}ms", response.took());
    }

刪除文檔

    @Async
    public void deleteDoc(Doc doc) {
        log.info("開始刪除es文檔,docNo={}", doc.getDocNo());
        // 構(gòu)建一個(gè)創(chuàng)建Doc的請(qǐng)求
        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("結(jié)束刪除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("結(jié)束修改es文檔,docNo={}", doc.getDocNo());
    }

查詢一個(gè)文檔

    /**
     * 根據(jù)文檔docNo查詢一個(gè)文檔
     *
     * @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 {
        // 分頁(yè)查詢
        SearchResponse<Doc> response = elasticsearchClient.search(s -> searchConditionBuilder(param, s)
                , Doc.class);
        log.info("檢索完成,耗時(shí)={}ms,hit總數(shù)={}", 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檢索表達(dá)式
     *
     * @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());
		//排序字段為空,則使用默認(rèn)排序
        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);

方式三:文章來源地址http://www.zghlxwxcb.cn/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);

到了這里,關(guān)于springboo整合elasticSearch8 java client api的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • java-springboot整合ElasticSearch8.2復(fù)雜查詢

    近期有大數(shù)據(jù)項(xiàng)目需要用到es,而又是比較新的es版本,網(wǎng)上也很少有8.x的java整合教程,所有寫下來供各位參考。 首先 1.導(dǎo)包: 2.客戶端連接代碼EsUtilConfigClint: 一開始按照其他博主的方法,長(zhǎng)時(shí)間連接不操作查詢?cè)俅握{(diào)用查詢時(shí)會(huì)報(bào)錯(cuò)timeout,所以要設(shè)置RequestConfigCallback 3

    2024年02月11日
    瀏覽(16)
  • Elasticsearch8.x版本中RestHighLevelClient被棄用,新版本中全新的Java客戶端Elasticsearch Java API Client中常用API練習(xí)

    在Es7.15版本之后,es官方將它的高級(jí)客戶端RestHighLevelClient標(biāo)記為棄用狀態(tài)。同時(shí)推出了全新的java API客戶端Elasticsearch Java API Client,該客戶端也將在Elasticsearch8.0及以后版本中成為官方推薦使用的客戶端。 Elasticsearch Java API Client支持除Vector title search API和Find structure API之外的所有

    2023年04月08日
    瀏覽(25)
  • SpringBoot整合ElasticSearch之Java High Level REST Client

    SpringBoot整合ElasticSearch之Java High Level REST Client

    1 搭建SpringBoot工程 2 引入ElasticSearch相關(guān)坐標(biāo)。 3 編寫核心配置類 編寫核心配置文件: 這里可以不寫在配置,可以直接寫在代碼中,只是一般都是寫在配置文件中 編寫核心配置類 4 測(cè)試客戶端對(duì)象 記得把maven的單元測(cè)試關(guān)了 注意:使用@Autowired注入RestHighLevelClient 如果報(bào)紅線

    2024年02月05日
    瀏覽(48)
  • SpringBoot整合最新Elasticsearch Java API Client 7.16教程

    SpringBoot整合最新Elasticsearch Java API Client 7.16教程

    ????最新在學(xué)習(xí)SpringBoot整合es的一些知識(shí),瀏覽了網(wǎng)上的一些資料,發(fā)現(xiàn)全都是es很久之前的版本了,其中比較流行的是Java REST Client的High Level Rest Client版本,但是官方文檔的說明中,已經(jīng)申明該版本即將廢棄,不再進(jìn)行維護(hù)了。可見:官方文檔 ????目前官方推薦的版本是

    2023年04月24日
    瀏覽(33)
  • ElasticSearch8 - SpringBoot整合ElasticSearch

    springboot 整合 ES 有兩種方案,ES 官方提供的 Elasticsearch Java API Client 和 spring 提供的 [Spring Data Elasticsearch](Spring Data Elasticsearch) 兩種方案各有優(yōu)劣 Spring:高度封裝,用著舒服。缺點(diǎn)是更新不及時(shí),有可能無法使用 ES 的新 API ES 官方:更新及時(shí),靈活,缺點(diǎn)是太靈活了,基本是一

    2024年03月25日
    瀏覽(78)
  • springboot整合elasticsearch8

    1.引入maven依賴 2.application.yml添加配置 3.編寫config文件 啟動(dòng)demo項(xiàng)目,通過控制臺(tái)日志查看是否能夠正常連接es。 4.在DemoApplicationTests編寫簡(jiǎn)單測(cè)試操作es。

    2024年02月12日
    瀏覽(22)
  • springboot整合elasticsearch8組合條件查詢

    整合過程見上一篇文章 springboot整合elasticsearch8 1.es8多條件組合查詢 2.使用scroll進(jìn)行大數(shù)據(jù)量查詢

    2024年02月16日
    瀏覽(19)
  • springBoot整合ElasticSearch8.x版本

    導(dǎo)入依賴 ? 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日
    瀏覽(28)
  • SpringBoot3.0 整合 ElasticSearch8.5.0 及使用

    這兩個(gè)版本都是目前較新的版本,本文選用的依賴是 spring-boot-starter-data-elasticsearch:3.0 ,這個(gè)新版本也是改用了es的 elasticsearch-java API,全面推薦使用Lambda語法;另外SpringData本身推出了 Repository 功能(有些類似Mybatis-Plus)的功能,也支持注解簡(jiǎn)化開發(fā)。 Docker 快速部署 單機(jī) ela

    2024年02月11日
    瀏覽(22)
  • elasticsearch8和kibana部署以及與springboot整合遇到的坑

    elasticsearch8和kibana部署以及與springboot整合遇到的坑

    我本來使用的是最新版本的es 8.6.2。但是由于ik分詞器只更新到8.6.1,所以就更改為部署8.6.1。在過程中遇到一些問題,這里做一個(gè)總結(jié) 環(huán)境:windows10 elasticsearch版本:8.6.1 一、修改es 用戶密碼的方式 二、kibana 使用用戶名和密碼登錄 修改kibana.yml 文件 啟動(dòng)kibana一直閃退 解決方

    2024年02月02日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包