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

javaAPI操作Elasticsearch

這篇具有很好參考價值的文章主要介紹了javaAPI操作Elasticsearch。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

mapping屬性


mapping是對索引庫中文檔的約束, 常見的mapping屬性包括:

  • type: 字段數(shù)據(jù)類型,常見的簡單類型有:
    • 字符串: text(可分詞的文本), keyword(精確值, 例如: 品牌,國家)
    • 數(shù)值: long, integer, short, byte, double, float
    • 布爾: boolean
    • 日期: date
    • 對象: object
  • index: 是否創(chuàng)建索引, 默認(rèn)為true
  • analyzer: 使用哪種分詞器
  • properties: 該字段的子字段

索引庫操作


創(chuàng)建索引庫

PUT /zyw
{
  "mappings": {
    "properties": {
      "info": {
        "type": "text",
        "analyzer": "ik_smart"
      },
      "email": {
        "type": "keyword",
        "index": false
      },
      "name": {
        "type": "object",
        "properties": {
          "firstName": {
            "type": "keyword"
          },
          "lastName":{
            "type":"keyword"
          }
        }
      }
    }
  }
}

查看索引庫

GET /zyw
GET /zyw/_mapping
# 查看索引庫列表和健康狀態(tài)
GET /_cat/indices

刪除索引庫

DELETE /zyw

修改索引庫, 添加新字段

索引庫和mapping一旦創(chuàng)建無法修改, 但是可以添加新字段

PUT /zyw/_mapping
{
  "properties": {
    "age": {
      "type": "integer"
    }
  }
}

文檔操作


新增文檔

POST /zyw/_doc/1
{
  "info": "java是最好的語言",
  "email": "zy@163.com",
  "name": {
    "firstName": "云",
    "lastName": "趙"
  }
}

可以不指定id, es會自動生成id

查詢文檔

GET /zyw/_doc/1

刪除文檔

DELETE /zyw/_doc/1

修改文檔

  • 全量修改, 會刪除舊文檔, 添加新文檔
PUT /zyw/_doc/1
{
  "info": "java是最好的語言",
  "email": "zy@163.com",
  "name": {
    "firstName": "云",
    "lastName": "趙"
  }
}
  • 局部修改
POST /zyw/_update/1
{
  "doc": {
    "email": "test@163.com"
  }
}

RestClient操作索引庫


javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

  • 引入依賴
		<dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.12.1</version>
        </dependency>

注意:
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
springboot管理了elasticsearch的部分依賴, 查看springboot的依賴管理
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
我們需要在pom文件中定義這個版本值,覆蓋springboot的
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

  • HotelDoc.java
@Data
@NoArgsConstructor
public class HotelDoc {
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;
    private String pic;

    public HotelDoc(Hotel hotel) {
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
        this.pic = hotel.getPic();
    }
}
  • hotel索引庫
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "name": {
        "type": "text",
        "analyzer": "ik_max_word",
        "copy_to": "all"
      },
      "address": {
        "type": "keyword",
        "index": false
      },
      "price": {
        "type": "integer"
      },
      "score": {
        "type": "integer"
      },
      "brand": {
        "type": "keyword",
        "copy_to": "all"
      },
      "city": {
        "type": "keyword"
      },
      "starName": {
        "type": "keyword"
      },
      "business": {
        "type": "keyword",
        "copy_to": "all"
      },
      "location": {
        "type": "geo_point"
      },
      "pic": {
        "type": "keyword",
        "index": false
      },
      "all": {
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}

基于elasticsearch的規(guī)則, id用keyword

  • 操作索引庫
import com.zyw.elasticsearchdemo.constants.HotelConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

public class ElasticsearchDemoApplicationTests {

    private RestHighLevelClient client;


    /**
     * 刪除索引庫
     */
    @Test
    void deleteHotelIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

    /**
     * 判斷索引庫是否存在
     */
    @Test
    void existHotelIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("hotel");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists ? "索引庫已經(jīng)存在" : "索引庫不存在");
    }

    /**
     * 創(chuàng)建索引庫
     */
    @Test
    void createHotelIndex() throws IOException {
        // 1.創(chuàng)建request對象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        // 2.準(zhǔn)備請求的參數(shù), DSL語句
        request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
        // 3. 發(fā)送請求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

RestClient操作文檔


import cn.hutool.json.JSONUtil;
import com.zyw.elasticsearchdemo.mapper.HotelMapper;
import com.zyw.elasticsearchdemo.pojo.Hotel;
import com.zyw.elasticsearchdemo.pojo.HotelDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
public class ElasticsearchDemoApplicationTests1 {

    private RestHighLevelClient client;

    @Autowired
    private HotelMapper hotelMapper;


    /**
     * 刪除文檔
     */
    @Test
    void deleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("hotel", "200216665");
        client.delete(request, RequestOptions.DEFAULT);

    }

    /**
     * 修改文檔-局部更新, 全量和創(chuàng)建一樣
     */
    @Test
    void updateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("hotel", "200216665");
        request.doc("price", 2600, "starName", "六鉆");
        client.update(request, RequestOptions.DEFAULT);
    }

    /**
     * 查詢文檔
     */
    @Test
    void getDocument() throws IOException {
        // 準(zhǔn)備request對象
        GetRequest request = new GetRequest("hotel", "200216665");
        // 發(fā)送請求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        String json = response.getSourceAsString();
        HotelDoc hotelDoc = JSONUtil.toBean(json, HotelDoc.class);
        System.out.println(hotelDoc);
    }

    /**
     * 新增文檔
     */
    @Test
    void addDocument() throws IOException {
        // 根據(jù)id查詢酒店數(shù)據(jù)
        Hotel hotel = hotelMapper.selectById(200216665);
        // 轉(zhuǎn)換為文檔對象
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 準(zhǔn)備request對象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        // 準(zhǔn)備json文檔
        request.source(JSONUtil.toJsonStr(hotelDoc), XContentType.JSON);
        // 發(fā)送請求
        client.index(request, RequestOptions.DEFAULT);
    }

    /**
     * 批量導(dǎo)入文檔
     */
    @Test
    void batchAddDocument() throws IOException {
        List<Hotel> hotels = hotelMapper.selectList(null);
        BulkRequest request = new BulkRequest();
        for (Hotel hotel : hotels) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            request.add(new IndexRequest("hotel").id(hotelDoc.getId().toString())
                    .source(JSONUtil.toJsonStr(hotelDoc), XContentType.JSON));
        }
        // 發(fā)送
        client.bulk(request, RequestOptions.DEFAULT);
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

DSL查詢語法


分類和基本語法

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

全文檢索查詢

全文檢索查詢, 會對用戶輸入內(nèi)容分詞, 常用于搜索框搜索
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
建議把多個字段copy到一個字段里

精確查詢

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

地理查詢

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

復(fù)合查詢

  • 復(fù)合(compound)查詢: 復(fù)合查詢可以將其他簡單查詢組合起來, 實現(xiàn)更復(fù)雜的搜索邏輯.
    • function score: 復(fù)分函數(shù)查詢, 可以控制文檔相關(guān)性算分, 控制文檔排名. 例如百度競價

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

搜索結(jié)果處理


排序

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

分頁

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

高亮

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
默認(rèn)字段要一致, 可以用require_field_match 取消一致

RestClient查詢文檔–高級查詢


javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

import cn.hutool.json.JSONUtil;
import com.zyw.elasticsearchdemo.pojo.HotelDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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

public class QueryDocumentTest {

    private RestHighLevelClient client;

    /**
     * 廣告置頂
     */
    @Test
    void adScore() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("city", "上海"));
        // 算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAd", true),
                        // 分?jǐn)?shù)10
                        ScoreFunctionBuilders.weightFactorFunction(10))
        }).boostMode(CombineFunction.SUM);  // 用加法 --> 分?jǐn)?shù)+10
        request.source().query(functionScoreQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * 高亮
     */
    @Test
    void testHighlight() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchQuery("all", "維也納"));
        // 高亮設(shè)置
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * 排序和分頁
     */
    @Test
    void sortAndPage() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().sort("price", SortOrder.ASC).from(20).size(5);
        request.source().query(QueryBuilders.matchAllQuery());
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * 根據(jù)地理坐標(biāo)排序
     */
    @Test
    void sortByLocation() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().sort(SortBuilders.geoDistanceSort("location",
                // 坐標(biāo)字符串前面是緯度,后面是經(jīng)度
                new GeoPoint("31.21, 121.5")).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
        request.source().query(QueryBuilders.matchQuery("all", "如家"));
        // 高亮設(shè)置
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);

    }

    /**
     * bool查詢
     * @throws IOException
     */
    @Test
    void testBool() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 添加term
        boolQuery.must(QueryBuilders.termQuery("city", "上海"));
        // 添加range
        boolQuery.filter(QueryBuilders.rangeQuery("price").lte(500));
        request.source().query(boolQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

	/**
     * bool查詢 --should
     * @throws IOException
     */
    @Test
    void testBool() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery();
        shouldQuery.should(QueryBuilders.matchQuery("name", "上海")).should(QueryBuilders.matchQuery("name","北京"));
        shouldQuery.minimumShouldMatch(1); // name中有上?;蛘弑本?滿足一個
        boolQuery.must(shouldQuery);
        // 添加range
        boolQuery.filter(QueryBuilders.rangeQuery("price").lte(180));
        request.source().query(boolQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * match查詢
     */
    @Test
    void testMatch() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchQuery("all", "如家"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * 處理結(jié)果
     * @param response
     */
    private static void handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 查詢的總條數(shù)
        long total = searchHits.getTotalHits().value;
        System.out.println("total = " + total);
        // 查詢的結(jié)果數(shù)組
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            // 得到source
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSONUtil.toBean(json, HotelDoc.class);
            // 獲取高亮結(jié)果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(!highlightFields.isEmpty()){
                // 根據(jù)字段名獲取高亮結(jié)果
                HighlightField highlightField = highlightFields.get("name");
                // 獲取高亮值
                String name = highlightField.getFragments()[0].toString();
                // 覆蓋非高亮結(jié)果
                hotelDoc.setName(name);
            }
            // 獲取location距離排序值 --> 距離4.5km
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length != 0) {
                hotelDoc.setDistance(sortValues[0]);
            }
            System.out.println("hotelDoc = " + hotelDoc);
        }
    }


    /**
     * 查詢所有
     * @throws IOException
     */
    @Test
    void testMatchAll() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchAllQuery());
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

數(shù)據(jù)聚合


javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

Bucket聚合

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

Metrics聚合

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

  • 指定排序字段
    javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

RestClient實現(xiàn)聚合


javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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

public class AggregationTest {

    private RestHighLevelClient client;

    /**
     * 品牌, 城市聚合
     * example --> {品牌=[7天酒店, 如家, 皇冠假日, 速8, 萬怡, 華美達, 和頤, 萬豪, 喜來登, 希爾頓], 城市=[上海, 北京, 深圳]}
     */
    @Test
    void name() throws IOException {
        Map<String, List<String>> result = new HashMap<>();
        SearchRequest request = new SearchRequest("hotel");
        // TODO  可以增加查詢條件過濾,條件和前面一樣,對滿足的文檔進行聚合
        request.source().size(0); // 去掉文檔,只看聚合結(jié)果
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg") // 名稱自己定
                .field("brand")
                .size(10));  // 結(jié)果的前十條
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg") // 名稱自己定
                .field("city")
                .size(10));  // 結(jié)果的前十條
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 處理結(jié)果
        Aggregations aggregations = response.getAggregations();
        List<String> brandList = getAggByName(aggregations, "brandAgg");
        result.put("品牌", brandList);
        List<String> cityList = getAggByName(aggregations, "cityAgg");
        result.put("城市", cityList);
        System.out.println(result);
    }

    private static List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms brandterms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandterms.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());
        }
        return list;
    }


    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

拼音分詞器


github地址: https://github.com/infinilabs/analysis-pinyin
解壓放到elasticsearch插件目錄
重啟elasticsearch

  • 測試
POST /_analyze
{
  "text": "我們都是祖國的花朵",
  "analyzer": "pinyin"
}

自定義分詞器

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
測試自定義分詞器

GET /test/_analyze
{
  "text": "java是最好的語言",
  "analyzer": "my_analyzer"
}

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

自動補全

javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

RestApi實現(xiàn)自動補全


javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎
javaAPI操作Elasticsearch,elasticsearch,大數(shù)據(jù),搜索引擎

  • hotel索引庫
PUT /hotel
{
  "settings": {
    "analysis": {
      "analyzer": {
        "text_anlyzer": {
          "tokenizer": "ik_max_word",
          "filter": "py"
        },
        "completion_analyzer": {
          "tokenizer": "keyword",
          "filter": "py"
        }
      },
      "filter": {
        "py": {
          "type": "pinyin",
          "keep_full_pinyin": false,
          "keep_joined_full_pinyin": true,
          "keep_original": true,
          "limit_first_letter_length": 16,
          "remove_duplicated_term": true,
          "none_chinese_pinyin_tokenize": false
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "id":{
        "type": "keyword"
      },
      "name":{
        "type": "text",
        "analyzer": "text_anlyzer",
        "search_analyzer": "ik_smart",
        "copy_to": "all"
      },
      "address":{
        "type": "keyword",
        "index": false
      },
      "price":{
        "type": "integer"
      },
      "score":{
        "type": "integer"
      },
      "brand":{
        "type": "keyword",
        "copy_to": "all"
      },
      "city":{
        "type": "keyword"
      },
      "starName":{
        "type": "keyword"
      },
      "business":{
        "type": "keyword",
        "copy_to": "all"
      },
      "location":{
        "type": "geo_point"
      },
      "pic":{
        "type": "keyword",
        "index": false
      },
      "all":{
        "type": "text",
        "analyzer": "text_anlyzer",
        "search_analyzer": "ik_smart"
      },
      "suggestion":{
          "type": "completion",
          "analyzer": "completion_analyzer",
       	  "search_analyzer": "ik_smart"
      }
    }
  }
}
  • HotelDoc.java

增加suggestion字段文章來源地址http://www.zghlxwxcb.cn/news/detail-844094.html

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Data
@NoArgsConstructor
public class HotelDoc {
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;
    private String pic;
    private Object distance;
    private Boolean isAd;
    private List<String> suggestion;

    public HotelDoc(Hotel hotel) {
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
        this.pic = hotel.getPic();
        if(this.business.contains("/")){
            // business有多個值,切割
            String[] arr = this.business.split("/");
            this.suggestion = new ArrayList<>();
            this.suggestion.add(this.brand);
            Collections.addAll(this.suggestion, arr);
        }else{
            this.suggestion = Arrays.asList(this.brand,this.business);
        }
    }
}
  • 查詢和解析結(jié)果
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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

public class SuggestionTest {

    private RestHighLevelClient client;


    /**
     * 自動補全
     */
    @Test
    void test() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("suggestions",  // 名稱自定義 解析結(jié)果時要與此保持一致
                SuggestBuilders.completionSuggestion("suggestion") // HotelDoc定義的字段
                .prefix("sd")  // 關(guān)鍵字
                 .skipDuplicates(true).size(10))
        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Suggest suggest = response.getSuggest();
        CompletionSuggestion suggestions = suggest.getSuggestion("suggestions"); // 名稱和上面一致
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            System.out.println(text);
        }
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

補充


  • 分詞
POST /_analyze
{
  "text": "java是最好的語言",
  "analyzer": "ik_smart"
}
  • 查所有
GET /hotel/_search

到了這里,關(guān)于javaAPI操作Elasticsearch的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

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

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

相關(guān)文章

  • 使用Elasticsearch進行數(shù)據(jù)批量操作

    Elasticsearch是一個開源的搜索和分析引擎,基于Lucene庫開發(fā)。它可以用來實現(xiàn)文本搜索、數(shù)據(jù)分析、實時數(shù)據(jù)處理等功能。在大數(shù)據(jù)時代,Elasticsearch成為了處理和分析大量數(shù)據(jù)的首選工具之一。 數(shù)據(jù)批量操作是Elasticsearch中的一種常見操作,它可以用來對大量數(shù)據(jù)進行創(chuàng)建、更

    2024年02月22日
    瀏覽(32)
  • Java操作Elasticsearch(新增數(shù)據(jù))

    Java操作Elasticsearch(新增數(shù)據(jù))

    天行健,君子以自強不息;地勢坤,君子以厚德載物。 每個人都有惰性,但不斷學(xué)習(xí)是好好生活的根本,共勉! 文章均為學(xué)習(xí)整理筆記,分享記錄為主,如有錯誤請指正,共同學(xué)習(xí)進步。 首先需要準(zhǔn)備好elasticsearch和kibana elasticsearch的下載、安裝、使用可參考:Elasticsearch安裝

    2024年02月03日
    瀏覽(16)
  • Spring Data Elasticsearch - 在Spring應(yīng)用中操作Elasticsearch數(shù)據(jù)庫

    Spring Data Elasticsearch為文檔的存儲,查詢,排序和統(tǒng)計提供了一個高度抽象的模板。使用Spring Data ElasticSearch來操作Elasticsearch,可以較大程度的減少我們的代碼量,提高我們的開發(fā)效率。 要使用Elasticsearch我們需要引入如下依賴: 還需要在配置文件中增加如下配置 類比于MyBat

    2024年02月14日
    瀏覽(19)
  • elasticsearch|大數(shù)據(jù)|elasticsearch的api部分實戰(zhàn)操作以及用戶和密碼的管理

    elasticsearch|大數(shù)據(jù)|elasticsearch的api部分實戰(zhàn)操作以及用戶和密碼的管理

    本文主要內(nèi)容是通過elasticsearch的api來進行一些集群的管理和信息查詢工作,以及elasticsearch用戶的增刪改查和密碼的重設(shè)以及重置如何操作 接上文: elasticsearch|大數(shù)據(jù)|elasticsearch低版本集群的部署安裝和安全增強---密碼設(shè)置問題-CSDN博客 上文主要介紹了elasticsearch低版本集群的

    2024年02月04日
    瀏覽(17)
  • 常規(guī)操作elasticSearch查看和索引(存儲)數(shù)據(jù)

    常規(guī)操作elasticSearch查看和索引(存儲)數(shù)據(jù)

    常規(guī)操作elasticSearch: 對于elasticSearch的操作 通常用rest API完成 查看所有節(jié)點: 示例返回: 查看健康狀態(tài): 示例返回: 查看主節(jié)點: 示例返回: 查看所有索引(類比mysql查看所數(shù)據(jù)庫): 示例返回: 保存一條數(shù)據(jù) put 保存: 注意: put保存必須有id(唯一識別) 示例返回:

    2023年04月08日
    瀏覽(25)
  • Java操作Elasticsearch進行數(shù)據(jù)檢索

    Java操作Elasticsearch進行數(shù)據(jù)檢索

    1.安裝依賴 (注意版本要和自己安裝的es版本對應(yīng)) ?????????打開發(fā)現(xiàn)部分依賴和我們es版本不一致,是因為springboot指定了版本,我們需要更換為自己對應(yīng)版本。 1.1、改為自己es對應(yīng)版本 ?2.編寫配置類 3.配置類添加請求選項 4、測試 4.1、存儲數(shù)據(jù)到es ?4.2、檢索數(shù)據(jù) ?

    2024年02月16日
    瀏覽(18)
  • (Rest風(fēng)格API)Elasticsearch索引操作、映射配置、數(shù)據(jù)操作、查詢操作

    (Rest風(fēng)格API)Elasticsearch索引操作、映射配置、數(shù)據(jù)操作、查詢操作

    1.請求方式:put 2.請求路徑:索引庫名 3.請求參數(shù):json格式 number_of_shards 是指索引要做多少個分片,只能在創(chuàng)建索引時指定,后期無法修改。 number_of_replicas 是指每個分片有多少個副本,后期可以動態(tài)修改 什么是分片? ES中所存數(shù)據(jù)的文件塊,也是數(shù)據(jù)的最小單元塊。假如有

    2024年04月26日
    瀏覽(21)
  • Elasticsearch ES操作:查詢數(shù)據(jù)(全部、分頁、單條)

    查詢 條件查詢 指定條數(shù) 返回結(jié)果

    2024年02月16日
    瀏覽(25)
  • (五) ElasticSearch 數(shù)據(jù)類型和文檔CRUD操作

    (五) ElasticSearch 數(shù)據(jù)類型和文檔CRUD操作

    官方文檔地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html#_complex_datatypes 核心數(shù)據(jù)類型是 Elasticsearch 最基本和常用的數(shù)據(jù)類型,用于存儲大部分?jǐn)?shù)據(jù)。這些核心數(shù)據(jù)類型包括: Text(文本):用于存儲長文本數(shù)據(jù),進行全文搜索和分析。 Keyword():

    2024年02月11日
    瀏覽(17)
  • Spring Boot 中的 Elasticsearch 的數(shù)據(jù)操作配置

    Spring Boot 中的 Elasticsearch 的數(shù)據(jù)操作配置

    Elasticsearch是一個基于Lucene的搜索引擎,可以快速地存儲、搜索和分析大量的數(shù)據(jù)。Spring Boot是一個開發(fā)框架,提供了快速構(gòu)建基于Spring的應(yīng)用程序的工具和技術(shù)。在本文中,我們將討論如何在Spring Boot應(yīng)用程序中配置Elasticsearch數(shù)據(jù)操作。 Elasticsearch是一個開源的全文搜索和分

    2024年02月05日
    瀏覽(24)

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包