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

ElasticSearch(九)【SpringBoot整合】

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

九、SpringBoot整合Elasticsearch


上一篇文章《ElasticSearch - 過(guò)濾查詢》

9.1 基本環(huán)境配置

  1. 創(chuàng)建一個(gè)springboot工程springboot-elasticsearch
  2. pom.xml導(dǎo)入依賴
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

注意】使用的springboot需要根當(dāng)前ES版本兼容

abstractelasticsearchconfiguration,ElasticSearch,elasticsearch,spring boot,java

  1. 配置application.yml文件
# 應(yīng)用名稱
spring:
  application:
    name: springboot-elasticsearch
# web端口號(hào)
server:
  port: 3035
# 自定義es主機(jī)和端口號(hào):
es:
  host: 192.168.159.100:9200
  1. 配置客戶端

創(chuàng)建config包,添加配置類RestClientConfiguration.class

package com.vinjcent.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

// ES 配置類
@Configuration
public class RestClientConfiguration extends AbstractElasticsearchConfiguration {

    @Value("${es.host}")
    private String host;

    @Bean
    @Override   // ES 兩個(gè)端口,一個(gè)是9200(rest方式通信),一個(gè)是9300(tcp方式通信)
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(host)
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

配置完之后,該配置類不僅會(huì)創(chuàng)建RestHighLevelClient的bean,還會(huì)幫我們創(chuàng)建一個(gè)叫做ElasticsearchOperations客戶端對(duì)象

為什么要提供這兩個(gè)對(duì)象呢?

因?yàn)镾pring Data在封裝ES操作的時(shí)候,完全站在了兩個(gè)角度去考慮

  • ElasticsearchOperations這個(gè)bean在操作ES的時(shí)候,主要以對(duì)象作為基礎(chǔ)去操作,ElasticsearchOperations序列化對(duì)象之后傳遞給ES,ES在查詢到結(jié)果之后,反序列化傳遞給ElasticsearchOperations
  • RestHighLevelClient更像于可視化的Kibana,通過(guò)rest的方式與ES進(jìn)行交互(企業(yè)多用,推薦使用)

9.2 ElasticsearchOperations

  • 特點(diǎn):始終使用面向?qū)ο蠓绞讲僮鱁S
    • 索引:用來(lái)存放相似文檔的集合
    • 映射:用來(lái)決定放入文檔的每個(gè)字段以什么樣方式錄入到ES中,字段類型、字段分詞器…
    • 文檔:可以被索引最小單元,json數(shù)據(jù)格式

使用ElasticsearchOperations進(jìn)行增刪查改操作

  1. 創(chuàng)建一個(gè)Product實(shí)體類
package com.vinjcent.pojo;


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;

import java.io.Serializable;

/**
 * @Document: 將這個(gè)類對(duì)象轉(zhuǎn)為 es 中一條文檔進(jìn)行錄入
 * indexName: 用來(lái)指定文檔的索引名稱
 * createIndex: 用來(lái)指定是否創(chuàng)建索引,默認(rèn)為false
 */
@Document(indexName = "products", createIndex = true)
public class Product implements Serializable {

    @Id // 用來(lái)將放入對(duì)象id值作為文檔_id進(jìn)行映射
    private Integer id;

    @Field(type = FieldType.Keyword)    // 字段映射類型
    private  String title;

    @Field(type = FieldType.Double)
    private Double price;

    @Field(type = FieldType.Text)
    private String description;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", price=" + price +
                ", description='" + description + '\'' +
                '}';
    }
}

  1. 在使用SpringBoot操作之前,將索引記錄刪除
# 查詢索引
GET /_cat/indices?v

# 刪除索引
DELETE /product

# 查看索引映射
GET /products/_mapping

# 查看數(shù)據(jù)
GET /products/_search
{
  "query": {
    "match_all": {}
  }
}
  1. 使用Java操作ES進(jìn)行增、刪、查、改、
package com.vinjcent;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vinjcent.pojo.Product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Query;

@SpringBootTest
public class ElasticSearchOperationsTest{

    private final ElasticsearchOperations elasticsearchOperations;

    @Autowired
    public ElasticSearchOperationsTest(ElasticsearchOperations elasticsearchOperations) {
        this.elasticsearchOperations = elasticsearchOperations;
    }

    /**
     * save 索引一條文檔 或 更新一條文檔
     * save 方法當(dāng)文檔id不存在時(shí)添加文檔,當(dāng)文檔id存在時(shí)候更新文檔
     */
    @Test
    public void testSave() {
        Product product = new Product();
        product.setId(1);
        product.setPrice(2.5);
        product.setTitle("vinjcent的妙妙屋");
        product.setDescription("真是米奇妙妙屋,妙到了家");
        elasticsearchOperations.save(product);
    }

    /**
     * query 根據(jù)id查詢一條文檔
     */
    @Test
    public void testQuery() {
        Product product = elasticsearchOperations.get("1", Product.class);
        System.out.println(product);
    }

    /**
     * delete 根據(jù)id刪除一條文檔
     */
    @Test
    public void testDelete() {
        Product product = new Product();
        product.setId(1);
        String delete = elasticsearchOperations.delete(product);
        System.out.println(delete);
    }

    /**
     * delete 刪除所有
     */
    @Test
    public void testDeleteAll() {
        elasticsearchOperations.delete(Query.findAll(), Product.class);
    }

    /**
     * 查詢所有
     */
    @Test
    public void testQueryAll() throws JsonProcessingException {
        SearchHits<Product> productSearchHits = elasticsearchOperations.search(Query.findAll(), Product.class);
        System.out.println("總分?jǐn)?shù): " + productSearchHits.getMaxScore());
        System.out.println("符合條件總數(shù): " + productSearchHits.getTotalHits());
        for (SearchHit<Product> productSearchHit : productSearchHits) {
            System.out.println(new ObjectMapper().writeValueAsString(productSearchHit.getContent()));
        }
    }

}

abstractelasticsearchconfiguration,ElasticSearch,elasticsearch,spring boot,java

abstractelasticsearchconfiguration,ElasticSearch,elasticsearch,spring boot,java

abstractelasticsearchconfiguration,ElasticSearch,elasticsearch,spring boot,java

9.3 RestHighLevelClient

使用RestHighLevelClient進(jìn)行索引操作

  1. 在使用SpringBoot操作之前,將索引記錄刪除
# 查詢索引
GET /_cat/indices?v

# 刪除索引
DELETE /products

# 查看數(shù)據(jù)
GET /products/_search
{
  "query": {
    "match_all": {}
  }
}
  1. 測(cè)試類RestHighLevelClientTests.class
package com.vinjcent;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class RestHighLevelClientTests {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public RestHighLevelClientTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    /**
     * 創(chuàng)建索引、映射
     */
    @Test
    public void testIndexAndMapping() throws IOException {

        // 1.創(chuàng)建索引請(qǐng)求對(duì)象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("products");
        // 2.指定映射,參數(shù)1: 指定映射json結(jié)構(gòu)     參數(shù)2: 指定映射類型
        createIndexRequest.mapping("{\n" +
                "    \"properties\": {\n" +
                "      \"title\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"price\": {\n" +
                "        \"type\": \"double\"\n" +
                "      },\n" +
                "      \"create_time\": {\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"description\": {\n" +
                "        \"type\": \"text\", \n" +
                "        \"analyzer\": \"ik_max_word\"\n" +
                "      }\n" +
                "    }\n" +
                "  }", XContentType.JSON);

        // 參數(shù)1: 創(chuàng)建索引請(qǐng)求對(duì)象    參數(shù)2: 請(qǐng)求配置對(duì)象
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println("創(chuàng)建狀態(tài): " + createIndexResponse.isAcknowledged());

        restHighLevelClient.close();    // 關(guān)閉資源
    }

    /**
     * 刪除索引
     * @throws IOException
     */
    @Test
    public void testDeleteIndex() throws IOException {
        // 參數(shù)1: 創(chuàng)建索引請(qǐng)求對(duì)象    參數(shù)2: 請(qǐng)求配置對(duì)象
        AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(new DeleteIndexRequest("products"), RequestOptions.DEFAULT);
        System.out.println(acknowledgedResponse.isAcknowledged());
    }


}

abstractelasticsearchconfiguration,ElasticSearch,elasticsearch,spring boot,java

abstractelasticsearchconfiguration,ElasticSearch,elasticsearch,spring boot,java

使用RestHighLevelClient進(jìn)文檔操作

package com.vinjcent;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class RestHighLevelClientForDocumentTests {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    /**
     * 創(chuàng)建一條文檔
     * @throws IOException
     */
    @Test
    public void testCreateDocu() throws IOException {
        // 1.創(chuàng)建索引對(duì)象
        IndexRequest indexRequest = new IndexRequest("products");
        // 2.配置創(chuàng)建的文檔對(duì)象
        indexRequest.id("1")    // 手動(dòng)指定文檔的id
                .source("{\n" +     // 文檔的數(shù)據(jù)內(nèi)容
                "  \"title\": \"vinjcent米奇妙妙屋\",\n" +
                "  \"price\": 21.5,\n" +
                "  \"create_time\": \"2022-09-16\",\n" +
                "  \"description\": \"真是妙到家了!\"\n" +
                "}",XContentType.JSON);
        // 3.接收請(qǐng)求后的索引響應(yīng)對(duì)象,參數(shù)1: 索引請(qǐng)求對(duì)象  參數(shù)2: 請(qǐng)求配置對(duì)象
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println(indexResponse.status());
    }

    /**
     * 更新一條文檔
     * @throws IOException
     */
    @Test
    public void testUpdateDocu() throws IOException {

        // 1.創(chuàng)建更新請(qǐng)求對(duì)象
        UpdateRequest updateRequest = new UpdateRequest("products", "2");

        // 2.配置doc文檔對(duì)象
        updateRequest.doc("{\n" +
                "    \"title\": \"totoro--的米奇妙妙屋\"\n" +
                "  }", XContentType.JSON);

        // 參數(shù)1: 更新請(qǐng)求對(duì)象  參數(shù)2: 請(qǐng)求配置對(duì)象
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);

        System.out.println(updateResponse.status());
    }

    /**
     * 刪除一條文檔
     * @throws IOException
     */
    @Test
    public void testDeleteDocu() throws IOException {

        // 參數(shù)1: 更新請(qǐng)求對(duì)象  參數(shù)2: 請(qǐng)求配置對(duì)象
        DeleteResponse deleteResponse = restHighLevelClient.delete(new DeleteRequest("products", "2"), RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
    }

    /**
     * 基于id查詢一條文檔
     * @throws IOException
     */
    @Test
    public void testQueryByIdDocu() throws IOException {
	    // 1.聲明get請(qǐng)求對(duì)象
        GetRequest getRequest = new GetRequest("products", "1");
        // 2.接收響應(yīng)對(duì)象		參數(shù)1: 獲取請(qǐng)求對(duì)象  參數(shù)2: 請(qǐng)求配置對(duì)象
        GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);

        System.out.println("id: " + getResponse.getId());

        System.out.println("source: " + getResponse.getSourceAsString());


    }


}

9.4 RestHighLevelClient 查詢操作

package com.vinjcent;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class RestHighLevelClientForDocumentTests {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    /**
     * 查詢所有
     */
    @Test
    public void testMatchAll() throws IOException {
        // 1.搜索請(qǐng)求對(duì)象
        SearchRequest searchRequest = new SearchRequest("products");

        // 2.指定條件對(duì)象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 3.配置請(qǐng)求對(duì)象中的條件對(duì)象
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());  // 查詢所有
        searchRequest.source(searchSourceBuilder);

        // 參數(shù)1: 搜索的請(qǐng)求對(duì)象     參數(shù)2: 請(qǐng)求配置對(duì)象     返回值: 擦汗尋結(jié)果對(duì)象
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
        System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());

        // 獲取結(jié)果
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String id = hit.getId();
            System.out.println("source: " + hit.getSourceAsString());
        }
    }

    /**
     * 關(guān)鍵字查詢 term
     */
    @Test
    public void testTerm() throws IOException {
        query(QueryBuilders.termQuery("description","真是"));
    }

    /**
     * 范圍查詢 range
     */
    @Test
    public void testRange() throws IOException {
        query(QueryBuilders.rangeQuery("price").gt(0).lt(50));
    }

    /**
     * 前綴查詢 prefix
     */
    @Test
    public void testPrefix() throws IOException {
        query(QueryBuilders.prefixQuery("title", "vinjcent"));
    }

    /**
     * 通配符查詢 wildcard
     */
    @Test
    public void testWildcard() throws IOException {
        // "*"代表多個(gè)字符,"?"代表一個(gè)字符
        query(QueryBuilders.wildcardQuery("title", "vinjcent*"));
    }

    /**
     * 多id查詢 ids
     */
    @Test
    public void testIds() throws IOException {
        // "*"代表多個(gè)字符,"?"代表一個(gè)字符
        query(QueryBuilders.idsQuery().addIds("1","2"));
    }

    /**
     * 多字段查詢 multi_match
     */
    @Test
    public void testMultiMatch() throws IOException {
        // 如果查的字段分詞,會(huì)先進(jìn)行分詞處理,否則不進(jìn)行分詞處理
        query(QueryBuilders.multiMatchQuery("妙", "title","description"));
    }


    public void query(QueryBuilder queryBuilder) throws IOException {

        // 1.搜索請(qǐng)求對(duì)象
        SearchRequest searchRequest = new SearchRequest("products");

        // 2.指定條件對(duì)象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 3.配置請(qǐng)求對(duì)象中的條件對(duì)象
        searchSourceBuilder.query(queryBuilder);  // 關(guān)鍵字
        searchRequest.source(searchSourceBuilder);

        // 參數(shù)1: 搜索的請(qǐng)求對(duì)象     參數(shù)2: 請(qǐng)求配置對(duì)象     返回值: 擦汗尋結(jié)果對(duì)象
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
        System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());

        // 獲取結(jié)果
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println("id: " + hit.getId() + " source: " + hit.getSourceAsString());
        }
    }
}

9.5 RestHighLevelClient 高亮、分頁(yè)、排序

package com.vinjcent;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.Map;

@SpringBootTest
public class RestHighLevelClientForDocumentTests {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }


    /**
     * 分頁(yè)查詢     from 起始位置   size 分頁(yè)大小
     * 排序查詢     sort
     * 指定字段獲取   _source
     * 高亮查詢     highlight
     * @throws IOException
     */
    @Test
    public void testSearch() throws IOException {

        // 1.創(chuàng)建請(qǐng)求索引對(duì)象
        SearchRequest searchRequest = new SearchRequest("products");
        // 2.創(chuàng)建搜索條件對(duì)象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 3.創(chuàng)建高亮對(duì)象
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false)   // 注意: 開(kāi)啟高亮的字段必須可以分詞,不然查詢結(jié)果無(wú)效
                .preTags("<span style='color: red;'>")  // 配置高亮包裹前綴
                .postTags("</span>")                    // 配置高亮包裹后綴
                .field("description")                   // 指定高亮字段
                .field("title");                        // 指定高亮字段
        searchSourceBuilder.query(QueryBuilders.termQuery("description", "妙"))
                            .from(0)    // 起始位置
                            .size(2)    // 分頁(yè)大小,默認(rèn)返回是10條
                            .sort("price", SortOrder.DESC) // 指定排序字段以及排序方式
                            .fetchSource(null, new String[]{"create_time"})  // 參數(shù)1: 包含字段數(shù)組  參數(shù)2: 排除字段數(shù)組  注意,當(dāng)兩者結(jié)合使用時(shí),只有前者會(huì)生效
                            .highlighter(highlightBuilder);
        // 4.為請(qǐng)求對(duì)象配置搜素對(duì)象
        searchRequest.source(searchSourceBuilder);
        // 5.接收響應(yīng)對(duì)象
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
        System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());

        // 獲取結(jié)果
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println("id: " + hit.getId() + " source: " + hit.getSourceAsString());
            // 獲取高亮字段description
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields.containsKey("description")) {
                System.out.println("description高亮結(jié)果: " + highlightFields.get("description").fragments()[0]);    // 獲取的字段為數(shù)組形式
            }
            // 獲取高亮字段title
            if (highlightFields.containsKey("title")) {
                System.out.println("title高亮結(jié)果: " + highlightFields.get("title").fragments()[0]);    // 獲取的字段為數(shù)組形式
            }
        }
    }
}

9.6 RestHighLevelClient 過(guò)濾查詢

package com.vinjcent;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.Map;

@SpringBootTest
public class RestHighLevelClientForDocumentTests {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }


    /**
     * query    精確查詢,查詢計(jì)算文檔得分,并根據(jù)文檔得分進(jìn)行返回
     * filter query   過(guò)濾查詢,用來(lái)在大量數(shù)據(jù)中篩選出本地查詢相關(guān)數(shù)據(jù),不會(huì)計(jì)算文檔得分,會(huì)對(duì)數(shù)據(jù)進(jìn)行緩存
     * 注意: 當(dāng)兩種查詢一起使用時(shí),ES優(yōu)先執(zhí)行filter query,后執(zhí)行query
     */
    @Test
    public void testFilterQuery() throws IOException {

        // 1.創(chuàng)建請(qǐng)求索引對(duì)象
        SearchRequest searchRequest = new SearchRequest("products");
        // 2.創(chuàng)建搜索條件對(duì)象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 3.配置查詢條件
        searchSourceBuilder
                .query(QueryBuilders.matchAllQuery())
                // ids、exists、term、terms、range等等都可以修改
                .postFilter(QueryBuilders.termQuery("description", "妙"));

        // 4.為請(qǐng)求對(duì)象配置搜素對(duì)象
        searchRequest.source(searchSourceBuilder);
        // 5.接收響應(yīng)對(duì)象
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
        System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());

        // 獲取結(jié)果
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println("id: " + hit.getId() + " source: " + hit.getSourceAsString());
        }
    }


}

9.7 RestHighLevelClient 應(yīng)用使用JSON

package com.vinjcent;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vinjcent.pojo.Product;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class RestHighLevelClientForDocumentTests {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public RestHighLevelClientForDocumentTests(@Qualifier("elasticsearchClient") RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }


    /**
     * 在有索引映射的條件下
     * 將對(duì)象放入ES中,進(jìn)行序列化操作
     */
    @Test
    public void testAddDoc() throws IOException {
        Product product = new Product();
        product.setId(2);
        product.setPrice(5.2);
        product.setTitle("vinjcent米奇妙妙屋");
        product.setDescription("我的心可不冷");

        IndexRequest indexRequest = new IndexRequest("products");
        indexRequest.id(product.getId().toString())
                .source(new ObjectMapper().writeValueAsString(product), XContentType.JSON); // 使用spring中自帶的json對(duì)象轉(zhuǎn)換
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.status());
    }

    /**
     * 將對(duì)象從ES中讀取,進(jìn)行反序列化
     */
    @Test
    public void testGetDoc() throws IOException {
        // 1.創(chuàng)建請(qǐng)求對(duì)象
        SearchRequest searchRequest = new SearchRequest("products");

        // 2.創(chuàng)建搜索條件對(duì)象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 3. 高亮對(duì)象
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder
                .requireFieldMatch(false)
                .field("description")
                .preTags("<span style='color: red;'>")
                .postTags("</span>");
        // 4.指定查詢條件
        searchSourceBuilder
                .query(QueryBuilders.termQuery("description", "絕境"))
                .from(0)
                .size(10)
                .highlighter(highlightBuilder);
        // 5.為請(qǐng)求對(duì)象配置條件對(duì)象
        searchRequest.source(searchSourceBuilder);
        // 6.接收響應(yīng)對(duì)象
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println("總條數(shù): " + searchResponse.getHits().getTotalHits().value);
        System.out.println("最大得分: " + searchResponse.getHits().getMaxScore());

        List<Product> products = new ArrayList<>();
        // 獲取響應(yīng)結(jié)果對(duì)象
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());    // json格式
            Product product = new ObjectMapper().readValue(hit.getSourceAsString(), Product.class); // 將json轉(zhuǎn)為Product對(duì)象

            // 處理高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields.containsKey("description")) {
                // 獲取高亮后的屬性值,進(jìn)行修改
                product.setDescription(highlightFields.get("description").fragments()[0].toString());
            }

            products.add(product);

        }

        for (Product product : products) {
            System.out.println(product);
        }

    }
}

下一篇文章《ElasticSearch - 聚合查詢》文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-625501.html

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

本文來(lái)自互聯(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)文章

  • Elasticsearch是什么,如何學(xué)習(xí)Elasticsearch,整合SpringBoot

    Elasticsearch是什么,如何學(xué)習(xí)Elasticsearch,整合SpringBoot

    目錄 一、是什么Elasticsearch 二、Elasticsearch,整合SpringBoot 三、Elasticsearch的優(yōu)勢(shì)和應(yīng)用場(chǎng)景 ? Elasticsearch是一個(gè)開(kāi)源的搜索引擎,它采用Java語(yǔ)言編寫(xiě),使用Lucene作為核心搜索引擎,并在其基礎(chǔ)上構(gòu)建了分布式的、可擴(kuò)展的、實(shí)時(shí)的數(shù)據(jù)存儲(chǔ)和分析引擎 。Elasticsearch最初由Shay B

    2024年02月16日
    瀏覽(20)
  • SpringBoot 整合 ElasticSearch

    SpringBoot 整合 ElasticSearch

    ??開(kāi)始前給大家推薦一款很火的刷題、面試求職網(wǎng)站?? https://www.nowcoder.com/link/pc_csdncpt_xiaoying_java 索引Index 一組相似文檔的集合 一個(gè)索引就是一個(gè)擁有幾分相似特征的文檔的集合。比如說(shuō),你可以有一個(gè)商品數(shù)據(jù)的索引,一個(gè)訂單數(shù)據(jù)的索引,還有一個(gè)用戶數(shù)據(jù)的索引。一

    2023年04月08日
    瀏覽(18)
  • ElasticSearch(九)【SpringBoot整合】

    ElasticSearch(九)【SpringBoot整合】

    上一篇文章 《ElasticSearch - 過(guò)濾查詢》 9.1 基本環(huán)境配置 創(chuàng)建一個(gè)springboot工程 springboot-elasticsearch 在 pom.xml 導(dǎo)入依賴 【 注意 】使用的springboot需要根當(dāng)前ES版本兼容 配置 application.yml 文件 配置客戶端 創(chuàng)建config包,添加配置類 RestClientConfiguration.class 配置完之后,該配置類不僅

    2024年02月14日
    瀏覽(54)
  • 三.SpringBoot整合Elasticsearch

    三.SpringBoot整合Elasticsearch

    我們整合es直接給es發(fā)請(qǐng)求就可以了,但是現(xiàn)在有很多方式去調(diào)用es的接口,那都有那些呢? 訪問(wèn)es端口 訪問(wèn)方式 使用工具 缺點(diǎn) 9300 TCP transport-api.jar 不適配es版本,es 8.0之后棄用。 9200 HTTP JestClient 非官方,對(duì)應(yīng)es版本更新慢。 9200 HTTP RestTemplate 模擬發(fā)送http請(qǐng)求,但是很多請(qǐng)求

    2024年02月13日
    瀏覽(22)
  • ElasticSearch系列 - SpringBoot整合ES:ElasticSearch分析器

    1. ElasticSearch match 文本搜索的過(guò)程? Elasticsearch 的 match 查詢是一種基于文本匹配的查詢方式,它的搜索過(guò)程如下: ① 將查詢字符串分詞:Elasticsearch 會(huì)將查詢字符串分成一個(gè)個(gè)詞項(xiàng)(term),并去除停用詞(如“的”、“是”等常用詞匯)和標(biāo)點(diǎn)符號(hào)等無(wú)意義的字符。 ② 構(gòu)建

    2023年04月18日
    瀏覽(26)
  • Springboot整合Elasticsearch(Es)

    Springboot整合Elasticsearch(Es)

    首先 在測(cè)試類中引入RestHighLevelClient對(duì)象 其次 準(zhǔn)備一個(gè)User對(duì)象 3.1.1 創(chuàng)建索引 ?運(yùn)行結(jié)果:創(chuàng)建成功返回true 3.1.2 刪除索引 運(yùn)行結(jié)果:刪除成功返回true ?3.1.3 判斷索引是否存在 運(yùn)行結(jié)果:存在返回true,不存在返回false. 3.2.1 添加文檔 運(yùn)行結(jié)果:添加成功返回 CREATED 3.2.2 查詢文檔--

    2023年04月22日
    瀏覽(24)
  • springboot整合elasticsearch使用案例

    springboot整合elasticsearch使用案例

    完成搜索和分頁(yè) 添加品牌、城市、星級(jí)、價(jià)格等過(guò)濾功能 搜索我附近的酒店 ? ?讓指定的酒店在搜索結(jié)果中排名置頂 添加isAD字段

    2024年02月09日
    瀏覽(17)
  • SpringBoot整合ElasticSearch版本問(wèn)題

    最近在整個(gè)這兩個(gè)框架,發(fā)現(xiàn)老是版本對(duì)不上,不是缺少類,就是啟動(dòng)不了,美好的一下午就這樣浪費(fèi)了,多說(shuō)一句廢話,es的版本更新速度也太快了,如果spring boot已經(jīng)固定的,注意一下es的版本。 下面的這個(gè)鏈接是spring官方提供的兼容版本 springboot與elasticsearch兼容版本對(duì)應(yīng)

    2024年02月15日
    瀏覽(22)
  • SpringBoot 3整合Elasticsearch 8

    SpringBoot 3整合Elasticsearch 8

    官網(wǎng)說(shuō)明 本文使用最新的版本 springboot: 3.2.3 spring-data elasticsearch: 5.2.3 elasticsearch: 8.11.4 elasticsearch下載鏈接:https://www.elastic.co/cn/downloads/past-releases#elasticsearch 最新版可能不兼容,以spring官網(wǎng)為準(zhǔn) 使用 https 必須配置 username 和 password spring data的repository方便操作,類似jpa的操作

    2024年04月11日
    瀏覽(14)
  • ElasticSearch ( 六 ) 與SpringBoot整合

    https://www.elastic.co/guide/en/elasticsearch/client/java-rest/ 如果當(dāng)前springboot所默認(rèn)依賴的版本與es版本不相同 指明服務(wù)器的IP 6.4.1.實(shí)體類 6.4.2.Controller

    2024年02月11日
    瀏覽(19)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

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

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包