首頁 > 軟體

java操作elasticsearch詳細方法總結

2022-12-21 14:01:07

一、前言

上一篇我們通過kibana的視覺化介面,對es的索引以及檔案的常用操作做了畢竟詳細的總結,本篇將介紹如何使用java完成對es的操作,這也是實際開發中將要涉及到的。

二、java操作es的常用模式

目前,開發中使用java操作es,不管是框架整合,還是純粹的使用es的api,主要通過下面兩種方式:

  • rest-api,主流的像  RestHighLevelClient ;

  • 與springboot整合時的jpa操作,主要是 ElasticsearchRepository 相關的api;

上面兩種模式的api在開發中都可以方便的使用,相比之下,RestHighLevelClient相關的api靈活性更高,而ElasticsearchRepository 底層做了較多的封裝,學習和使用的成本更低,上手更快。

接下來將對上面的兩種操作模式做一個詳細的總結,本篇所述的es基於7.6.2版本,配合的kibana也為7.6.2版本。

三、rest-api 操作

1、前置準備

匯入依賴

匯入核心依賴,主要是es的rest依賴,其他的可以根據自己的需要匯入; 

<dependencies>
 
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.2</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.2</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-jcl</artifactId>
            <version>2.11.2</version>
        </dependency>
 
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
 
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.6.2</version>
        </dependency>
 
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.6.2</version>
        </dependency>
 
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
 
 
    </dependencies>

es連線測試

為了確保後續的所有實驗能夠正常進行,建議先通過下面的程式測試下是否能夠連線es服務;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
 
import java.io.IOException;
 
public class EsClientTest {
 
    public static void main(String[] args) throws IOException {
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("IP",9200,"http"))
        );
        System.out.println("success");
        esClient.close();
    }
 
}

執行上面的程式碼,出現下面的效果說明連線成功

2、索引相關操作api的使用

為了減少連線相關的編碼,我們將es的client提出到全域性的靜態變數中,其他方法中就可以直接參照了

    public static RestHighLevelClient esClient;
 
    static {
        esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("IP", 9200, "http"))
        );
    }

2.1  建立索引

    /**
     * 建立索引
     * @throws IOException
     */
    public static void createIndex() throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
        CreateIndexResponse indexResponse = esClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        boolean acknowledged = indexResponse.isAcknowledged();
        System.out.println("索引建立狀態:" + acknowledged);
    }

main方法中呼叫方法即可

public static void main(String[] args) throws IOException {
        System.out.println("connect success");
        createIndex();
        esClient.close();
}

執行main建立索引

通過kibana查詢確認索引是否建立成功

2.2  獲取索引

/**
     * 索引資訊查詢
     * @throws IOException
     */
    public static void getIndex() throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest("user");
        GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(getIndexResponse.getAliases());
        System.out.println(getIndexResponse.getMappings());
        System.out.println(getIndexResponse.getSettings());
    }

2.3  刪除索引

    /**
     * 刪除索引
     * @throws IOException
     */
    public static void deleteIndex() throws IOException {
        DeleteIndexRequest getIndexRequest = new DeleteIndexRequest("user");
        AcknowledgedResponse delete = esClient.indices().delete(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println("索引刪除狀態:" + delete.isAcknowledged());
    }

3、檔案常用操作api的使用

在實際開發過程中,對於檔案的操作更為的頻繁,接下來演示與es檔案相關的操作api。

前置準備

public static ObjectMapper objectMapper = new ObjectMapper();
 
    public static RestHighLevelClient esClient;
    static {
        esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("IP", 9200, "http"))
        );
    }

用於測試使用的物件

public class User {
 
    private String name;
    private String sex;
    private Integer age;
 
    private Integer salary;
 
    public User() {
    }
 
    public User(String name, String sex, Integer age, Integer salary) {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.salary = salary;
    }
 
    public Integer getSalary() {
        return salary;
    }
 
    public void setSalary(Integer salary) {
        this.salary = salary;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
}

3.1  索引新增檔案

注意:實際開發中,user物件應該作為引數傳入【可以基於此做進一步的封裝】

    /**
     * 新增資料
     * @throws Exception
     */
    public static void add() throws Exception{
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("user").id("1008");
        User user = new User();
        user.setName("孫二孃");
        user.setAge(23);
        user.setSex("女");
        user.setSalary(7000);
 
        String userData = objectMapper.writeValueAsString(user);
        indexRequest.source(userData,XContentType.JSON);
        //插入資料
        IndexResponse response = esClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());
        System.out.println(response.getResult());
    }

在main方法呼叫執行下該方法

public static void main(String[] args) throws Exception {
        add();
        esClient.close();
}

可以通過kibana查詢檢查下資料是否新增成功

3.2  修改檔案

    /**
     * 修改資料
     * @throws Exception
     */
    public static void update() throws Exception{
        UpdateRequest request = new UpdateRequest();
        request.index("user").id("1008");
        request.doc(XContentType.JSON,"name","母夜叉");
        //插入資料
        UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());
    }

3.3  刪除檔案

    /**
     * 刪除
     * @throws Exception
     */
    public static void delete() throws Exception{
        DeleteRequest request = new DeleteRequest();
        request.index("user").id("1008");
        //插入資料
        DeleteResponse delete = esClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.getResult());
    }

3.4  批次新增檔案

有些情況下,單條插入效率太低,可以使用es的批次插入功能一次性新增多條資料

    /**
     * 批次新增
     * @throws Exception
     */
    public static void batchInsert() throws Exception{
 
        BulkRequest bulkRequest = new BulkRequest();
 
        User user1 = new User("關羽","男",33,5500);
        String userData1 = objectMapper.writeValueAsString(user1);
        IndexRequest indexRequest1 = new IndexRequest().index("user").id("1002").source(userData1, XContentType.JSON);
 
        bulkRequest.add(indexRequest1);
 
        User user2 = new User("黃忠","男",50,8000);
        String userData2 = objectMapper.writeValueAsString(user2);
        IndexRequest indexRequest2 = new IndexRequest().index("user").id("1003").source(userData2, XContentType.JSON);
        bulkRequest.add(indexRequest2);
 
        User user3 = new User("黃忠2","男",49,10000);
        String userData3 = objectMapper.writeValueAsString(user3);
        IndexRequest indexRequest3 = new IndexRequest().index("user").id("1004").source(userData3, XContentType.JSON);
        bulkRequest.add(indexRequest3);
 
        User user4 = new User("趙雲","男",33,12000);
        String userData4 = objectMapper.writeValueAsString(user4);
        IndexRequest indexRequest4 = new IndexRequest().index("user").id("1005").source(userData4, XContentType.JSON);
        bulkRequest.add(indexRequest4);
 
        User user5 = new User("馬超","男",38,20000);
        String userData5 = objectMapper.writeValueAsString(user5);
        IndexRequest indexRequest5 = new IndexRequest().index("user").id("1006").source(userData5, XContentType.JSON);
        bulkRequest.add(indexRequest5);
 
        User user6 = new User("關羽","男",41,27000);
        String userData6 = objectMapper.writeValueAsString(user6);
        IndexRequest indexRequest6 = new IndexRequest().index("user").id("1007").source(userData6, XContentType.JSON);
        bulkRequest.add(indexRequest6);
 
        BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.status());
        System.out.println(bulkResponse.getItems());
    }

3.5  批次刪除

可以通過批次操作一次性刪除多條資料

    /**
     * 批次刪除
     * @throws Exception
     */
    public static void batchDelete() throws Exception{
        BulkRequest bulkRequest = new BulkRequest();
        DeleteRequest indexRequest1 = new DeleteRequest().index("user").id("1002");
        DeleteRequest indexRequest2 = new DeleteRequest().index("user").id("1003");
        DeleteRequest indexRequest3 = new DeleteRequest().index("user").id("1004");
        DeleteRequest indexRequest4 = new DeleteRequest().index("user").id("1005");
        DeleteRequest indexRequest5 = new DeleteRequest().index("user").id("1006");
        DeleteRequest indexRequest6 = new DeleteRequest().index("user").id("1007");
 
        bulkRequest.add(indexRequest1);
        bulkRequest.add(indexRequest2);
        bulkRequest.add(indexRequest3);
        bulkRequest.add(indexRequest4);
        bulkRequest.add(indexRequest5);
        bulkRequest.add(indexRequest6);
 
        BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.status());
        System.out.println(bulkResponse.getItems());
    }

 4、檔案搜尋相關api的使用

我們知道es最強大的功能就是檔案檢索了,接下來演示下與es檔案查詢相關的常用API的操作;

4.1  查詢某個索引下的所有資料

    /**
     * 查詢某個索引下的所有資料
     * @throws Exception
     */
    public static void searchIndexAll() throws Exception{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        // 索引中的全部資料查詢
        SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        request.source(query);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }
    }

執行一下對該方法的呼叫

這個效果和在kibana中下面的操作效果是一樣的

4.2  批次查詢多條資料

針對那種需要一次性查出多條資料的場景可以考慮使用

        MultiGetRequest multiGetRequest = new MultiGetRequest();
        multiGetRequest.add("user", "1002");
        multiGetRequest.add("user", "1003");
        MultiGetResponse responses = esClient
                .mget(multiGetRequest, RequestOptions.DEFAULT);
 
        Iterator<MultiGetItemResponse> iterator = responses.iterator();
        while (iterator.hasNext()){
            MultiGetItemResponse next = iterator.next();
            System.out.println(next.getResponse().getSourceAsString());
        }

4.3  根據條件精準查詢

根據性別查詢,有點類似於mysql 中的 where sex='女' 這樣的效果

        TermQueryBuilder ageQueryBuilder = QueryBuilders.termQuery("sex", "女");
        SearchSourceBuilder query = new SearchSourceBuilder().query(ageQueryBuilder);
        request.source(query);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.4  分頁查詢

考察from + size的使用

        SearchSourceBuilder sourceBuilder = new                         
        SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        sourceBuilder.from(0).size(3);
        request.source(sourceBuilder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.5  查詢結果按照某個欄位進行排序

將查詢結果按照age進行排序

        SearchSourceBuilder sourceBuilder = new     
        SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        sourceBuilder.sort("age",SortOrder.ASC);
        request.source(sourceBuilder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.6  查詢結果過濾某些欄位

類似於mysql中只查詢某個表的部分欄位

        SearchSourceBuilder sourceBuilder = new         
        SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        request.source(sourceBuilder);
        String[] includes = {"name","sex"};
        String[] excludes = {"age"};
        sourceBuilder.fetchSource(includes,excludes);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.7  多條件查詢

es可以像mysql那樣組合多個條件進行查詢,考察對BoolQuery的使用,如下:查詢性別為難男,年齡在35到45之間的使用者;

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("sex","男"));
        boolQueryBuilder.must(QueryBuilders.rangeQuery("age").lt(45).gt(35));
        sourceBuilder.query(boolQueryBuilder);
        request.source(sourceBuilder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
 
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.8  範圍查詢

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQueryBuilder =     
        QueryBuilders.rangeQuery("age").gte(35).lte(45);
        sourceBuilder.query(rangeQueryBuilder);
        request.source(sourceBuilder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.9  模糊查詢

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        FuzzyQueryBuilder fuzzyQueryBuilder =
                QueryBuilders.fuzzyQuery("name", "黃忠")
                        .fuzziness(Fuzziness.ONE);
        sourceBuilder.query(fuzzyQueryBuilder);
        request.source(sourceBuilder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.10   高亮查詢

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder ageQueryBuilder = QueryBuilders.termQuery("age", 33);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name");
        sourceBuilder.highlighter(highlightBuilder);
        sourceBuilder.query(ageQueryBuilder);
        request.source(sourceBuilder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.11  多欄位查詢multi_match

這個用法表示從多個欄位中匹配某個關鍵字

        SearchSourceBuilder builder = new SearchSourceBuilder();
        MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery("黃忠","name", "sex");
        multiMatchQuery.operator(Operator.OR);
        builder.query(multiMatchQuery);
        request.source(builder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.12  聚合查詢

        SearchSourceBuilder builder = new SearchSourceBuilder();
        AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
        builder.aggregation(aggregationBuilder);
        request.source(builder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

4.13  分組查詢

        SearchSourceBuilder builder = new SearchSourceBuilder();
        AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
        builder.aggregation(aggregationBuilder);
        request.source(builder);
 
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.getHits().getHits());
        System.out.println(response.getHits().getTotalHits());
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits){
            System.out.println(searchHit.getSourceAsString());
        }

四、與springboot 整合

es提供了與spring,springboot快速整合的第三方SDK,接下來以spring-data為例進行說明;

spring-boot-starter-data-elasticsearch 與spring其他相關的jpa方式使用類似,封裝了豐富的API介面,客戶只需要繼承其提供的介面,就能方便的使用內建的API

前置準備

本地建立一個maven工程

1、匯入核心依賴

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.6.RELEASE</version>
        <relativePath/>
    </parent>
 
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
    </dependencies>

2、核心組態檔

# es 服務地址
elasticsearch.host=IP
# es 伺服器埠
elasticsearch.port=9200
# 設定紀錄檔級別,開啟 debug 紀錄檔
logging.level.com.congge=debug

整合過程

1、建立一個實體類

該實體類屬於連線es檔案與使用者端的一箇中間轉換層,使用過jpa或者mybatis-plus的同學對這個應該不陌生;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
 
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "shopping", shards = 3, replicas = 1)
public class Product {
    //必須有 id,這裡的 id 是全域性唯一的標識,等同於 es 中的"_id"
    @Id
    private Long id;//商品唯一標識
 
    /**
     * type : 欄位資料型別
     * analyzer : 分詞器型別
     * index : 是否索引(預設:true)
     * Keyword : 短語,不進行分詞
     */
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String title;//商品名稱
 
    @Field(type = FieldType.Keyword)
    private String category;//分類名稱
 
    @Field(type = FieldType.Double)
    private Double price;//商品價格
 
    @Field(type = FieldType.Keyword, index = false)
    private String images;//圖片地址
}

2、提供一個介面,繼承ElasticsearchRepository

import com.congge.entity.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
 
@Repository
public interface ProductDao extends ElasticsearchRepository<Product, Long>{
 
}

3、核心設定類

import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
//import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
 
@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Data
public class EsConfig extends com.congge.config.AbstractElasticsearchConfiguration {
 
    private String host ;
    private Integer port ;
 
    //重寫父類別方法
    @Override
    public RestHighLevelClient elasticsearchClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
        RestHighLevelClient restHighLevelClient = new
                RestHighLevelClient(builder);
        return restHighLevelClient;
    }
}
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
 
public abstract class AbstractElasticsearchConfiguration extends ElasticsearchConfigurationSupport {
 
    //需重寫本方法
    public abstract RestHighLevelClient elasticsearchClient();
 
    @Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
    public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter) {
        return new ElasticsearchRestTemplate(elasticsearchClient(), elasticsearchConverter);
    }
}

模擬測試

接下來通過junit的方式進行測試

1、索引相關的操作測試

import com.congge.entity.Product;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsIndexTest {
 
    //注入 ElasticsearchRestTemplate
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
 
    //建立索引並增加對映設定
    @Test
    public void createIndex(){
        //建立索引,系統初始化會自動建立索引
        System.out.println("建立索引");
    }
 
    @Test
    public void deleteIndex(){
        //建立索引,系統初始化會自動建立索引
        boolean flg = elasticsearchRestTemplate.deleteIndex(Product.class);
        System.out.println("刪除索引 = " + flg);
    }
 
}

基於spring-data的方式,在工程啟動的時候,會自動讀取實體類相關的註解,自動完成索引的建立,執行下建立索引的測試方法;

然後去到kibana上面確認下是否建立成功;

2、檔案相關的操作測試

該測試類中列舉了常用的增刪改查操作

import com.congge.dao.ProductDao;
import com.congge.entity.Product;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
 
import java.util.ArrayList;
import java.util.List;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsDocTest {
 
 
    @Autowired
    private ProductDao productDao;
 
    /**
     * 新增
     */
    @Test
    public void save() {
        Product product = new Product();
        product.setId(2L);
        product.setTitle("ipad mini");
        product.setCategory("ipad");
        product.setPrice(1998.0);
        product.setImages("http://ipad.jpg");
        productDao.save(product);
    }
 
 
    //修改
    @Test
    public void update(){
        Product product = new Product();
        product.setId(2L);
        product.setTitle("iphone");
        product.setCategory("mobile");
        product.setPrice(6999.0);
        product.setImages("http://www.phone.jpg");
        productDao.save(product);
    }
 
    //根據 id 查詢
    @Test
    public void findById(){
        Product product = productDao.findById(2L).get();
        System.out.println(product);
    }
 
    //查詢所有
    @Test
    public void findAll(){
        Iterable<Product> products = productDao.findAll();
        for (Product product : products) {
            System.out.println(product);
        }
    }
 
    //刪除
    @Test
    public void delete(){
        Product product = new Product();
        product.setId(2L);
        productDao.delete(product);
    }
 
    //批次新增
    @Test
    public void saveAll(){
        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Product product = new Product();
            product.setId(Long.valueOf(i));
            product.setTitle("iphone" + i);
            product.setCategory("mobile");
            product.setPrice(5999.0 + i);
            product.setImages("http://www.phone.jpg");
            productList.add(product);
        }
        productDao.saveAll(productList);
    }
 
    //分頁查詢
    @Test
    public void findByPageable(){
        //設定排序(排序方式,正序還是倒序,排序的 id)
        Sort sort = Sort.by(Sort.Direction.DESC,"id");
        int currentPage=0;//當前頁,第一頁從 0 開始, 1 表示第二頁
        int pageSize = 5;//每頁顯示多少條
        //設定查詢分頁
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
        //分頁查詢
        Page<Product> productPage = productDao.findAll(pageRequest);
        for (Product Product : productPage.getContent()) {
            System.out.println(Product);
        }
    }
 
    /**
     * term 查詢
     * search(termQueryBuilder) 呼叫搜尋方法,引數查詢構建器物件
     */
    @Test
    public void termQuery(){
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "iphone");
        Iterable<Product> products = productDao.search(termQueryBuilder);
        for (Product product : products) {
            System.out.println(product);
        }
    }
 
    /**
     * term 查詢加分頁
     */
    @Test
    public void termQueryByPage(){
        int currentPage= 0 ;
        int pageSize = 5;
        //設定查詢分頁
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "phone");
        Iterable<Product> products =
                productDao.search(termQueryBuilder,pageRequest);
        for (Product product : products) {
            System.out.println(product);
        }
    }
 
}

測試其中批次新增的方法

更多豐富的API介面的使用有興趣的同學可以基於此繼續深入的研究學習。

總結

到此這篇關於java操作elasticsearch詳細方法的文章就介紹到這了,更多相關java操作elasticsearch內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com