Elasticsearch8.1-ElasticsearchClient-Java客戶端簡單增刪查改-隨筆


  • 環境准備
    1. Springboot 基本環境
      • 自行前往https://start.spring.io/ 構建一個即可
    2. Elasticsearch服務端
      • 簡單說下windows版本的安裝  https://www.elastic.co/cn/downloads/elasticsearch   下載最新版8.1.0,之后解壓 不要放到中文目錄下,進入bin目錄雙擊運行elasticsearch.bat.
  • 相關依賴
    1. pom.xml   ELasticsearch相關的依賴

      <dependency>
          <groupId>co.elastic.clients</groupId>
          <artifactId>elasticsearch-java</artifactId>
          <version>8.1.0</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.13.2</version>
      </dependency>
    2. application.yml
      elasticsearch:
        host: 127.0.0.1
        port: 9200

 


具體實現

首先要建立連接,這樣就能在后續使用springboot自動裝配

@Autowired
private ElasticsearchClient elasticsearchClient;

具體代碼如下

查看代碼
package cn.daimao.TestTryProject.bean;

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.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class ElasticClient {
    @Value("${elasticsearch.host}")
    private String host;
    @Value("${elasticsearch.port}")
    private Integer port;

    @Bean
    public ElasticsearchClient getClient() {
        RestClientBuilder builder = RestClient.builder(
                new HttpHost(host, port));
        ElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}

創建索引

@Autowired
private ElasticsearchClient elasticsearchClient;
@PostMapping("/createIndex")
public ResultJson createIndex(@RequestParam String indexName) throws IOException {
    elasticsearchClient.indices().create(createIndex -> createIndex.index(indexName));
    return ResultJson.success();
}

上傳文檔(數據)到索引

.index() 指定索引

.id() 設置該文檔的id 如果不設置則會自動生成

.document() 具體的對象

我這里用的TProduct 更換成自己需要檢索的分詞結構即可。

返回ResultJson 只是一個通用類不重要。

查看代碼
    public ResultJson uploadProduct(TProduct tProduct)  {
        IndexRequest<TProduct> req ;
        req = IndexRequest.of( b->
                b.index("product").id(tProduct.getProductId()+"").document(tProduct));
        try {
            elasticsearchClient.index(req);
            return ResultJson.success();
        } catch (IOException e) {
            return ResultJson.failure(e.toString());
        }
    }

修改指定索引的對應ID的文檔內容

.index() 指定索引

.id() 要修改的文檔的id,我上面上傳是用的TProduct對象的productId,所以這里也用這個屬性來更新

.doc() 修改后的對象

    public ResultJson updateDocument(TProduct tProduct){
        UpdateRequest<TProduct,TProduct> req;
        req = UpdateRequest.of(
                b-> b.index("product").id(tProduct.getProductId()+"")
                                .doc(tProduct)
        );
        try {
            elasticsearchClient.update(req,TProduct.class);
            return ResultJson.success();
        } catch (IOException e) {
            return ResultJson.failure(e.toString());
        }
    }

刪除指定索引的文檔

.index() 指定索引

.id() 要刪除的文檔的id,我上面上傳是用的TProduct對象的productId,所以這里也用這個屬性來更新

查看代碼
    public ResultJson deleteDocument(Long productId){
        DeleteRequest req ;
        req = DeleteRequest.of(
                b-> b.index("product").id(productId+"")
        );
        try {
            elasticsearchClient.delete(req);
            return ResultJson.success();
        } catch (IOException e) {
            return ResultJson.failure(e.toString());
        }
    }

查詢

tProductList 存放最后查詢hit到的結果集

調用客戶端的search方法,目前只寫了個matchQuery模糊查詢,后面是拿到response的處理,官網復制粘貼的---復雜查詢待補充

查看代碼
public ResultJson queryTest(String name) throws IOException {
        List<TProduct> tProductList = new ArrayList<>();

        SearchResponse<TProduct> response = elasticsearchClient.search(
                s -> s.index("product")
                        .query(
                                q -> q.match(
                                        t -> t.field("productName")
                                                .query(name)
                                )

                        )
                ,
                TProduct.class

        );
        TotalHits total = response.hits().total();
        boolean isExactResult = total.relation() == TotalHitsRelation.Eq;
        if (isExactResult) {
            log.info("There are {} results", total.value());
        } else {
            log.info("There are more than {} results", total.value());
        }
        List<Hit<TProduct>> hits = response.hits().hits();
        for (Hit<TProduct> hit : hits) {
            TProduct product = hit.source();
            tProductList.add(product);
        }
        return ResultJson.success(tProductList);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM