主頁 >  其他 > ElasticSearch-學習筆記

ElasticSearch-學習筆記

2020-12-29 14:03:05 其他

文章目錄

  • 前言
  • 1.簡介
  • 2.Es與MySql的對比
  • 3.Es與其他資料存盤組件比較
  • 4.特點
  • 5.倒排索引
  • 6.B+Tree
  • 7.ElasticSearch中的基本概念
  • 8.ElasticSearchRepository和ElasticSearchTemplate的使用
  • 9.FSCrawler(ElasticSearch的FS搜尋器,)
  • 10.RESTful API
  • 11.中文分詞
  • 12.動態同義詞(自定義)
  • 13.JavaAPI(實作ES的工具類,采用了高級API)
  • 總結


前言

本文分享本菜鳥的ElasticSearch筆記,
內容不是很多,也可能是我接觸的不夠深,
一起學習,一起進步 ~
本菜鳥QQ:599903582
笨鳥先飛,熟能生巧~
比心心 ~


提示:以下是本篇文章正文內容,下面案例可供參考

1.簡介

ES是一個基于RESTful web介面并且構建在Apache Lucence之上的開源分布式搜索引擎,分布式檔案資料庫,每個欄位均可被索引,每個字符的資料均可被搜索,能夠橫向拓展至數以百計的服務器存盤以及處理PB級的資料,

高可用 可拓展,
不支持事務,
檔案是可以被索引的基本單位,


2.Es與MySql的對比

在這里插入圖片描述
在這里插入圖片描述


3.Es與其他資料存盤組件比較

在這里插入圖片描述


4.特點

  • 天然分片,天然集群
    es 把資料分成多個shard,多個shard可以組成一份完整的資料,這些shard可以分布在集群中的各個機器節點中es 把資料分成多個shard,多個shard可以組成一份完整的資料,這些shard可以分布在集群中的各個機器節點中,
    在實際運算程序中,每個查詢任務提交到某一個節點,該節點必須負責將資料進行整理匯聚,再回傳給客戶端,也就是一個簡單的節點上進行Map計算,在一個固定的節點上進行Reduces得到最終結果向客戶端回傳,

  • 天然索引
    ES 所有資料都是默認進行索引的,這點和mysql正好相反,mysql是默認不加索引,要加索引必須特別說明,ES只有不加索引才需要說明,而ES使用的是倒排索引和Mysql的B+Tree索引不同,


5.倒排索引

索引:倒排索引 前面是欄位,后面是欄位對應的位置資訊
在這里插入圖片描述


6.B+Tree

在這里插入圖片描述


7.ElasticSearch中的基本概念

在這里插入圖片描述


8.ElasticSearchRepository和ElasticSearchTemplate的使用

(極大的簡化開發)

https://blog.csdn.net/tianyaleixiaowu/article/details/76149547

9.FSCrawler(ElasticSearch的FS搜尋器,)

https://fscrawler.readthedocs.io/en/latest/index.html

10.RESTful API

(ES7中型別_type已經均為_doc, 這里的是之前版本的指令)

PUT test01    // 建立mapping,然后可以往里傳資料 ,如果開始的時候沒有指定則根據第一條資料進行推測
{
  "mappings": {
    "person":{
      "properties":{
        "id":{
          "type":"keyword"
        },
        "name":{
          "type":"text"
        },
        "age":{
          "type":"integer"
        }
      }
    }
  }
}

PUT /test01/person/1     //往索引test01傳資料,person為_type, 1 為 _id
{
  "id":1,
  "name":"xuchenglei",
  "age":23
}

GET /test01/person/_search    //查詢 索引 test01 下 person型別的, 滿足match匹配的資料
{
  "query": {
    "match": {
      "name": "guomengyao"
    }
  }
}

GET /test01/person/_search
{
  "query": {
    "match": {
      "_type": "person"
    }
  }
}

GET /test01/person/_search    //得到索引test01下的person型別的所有資料

GET /_cat/nodes?v  查詢各個節點狀態
 
GET /_cat/indices?v  查詢各個索引狀態
 
GET /_cat/shard/xxxx  查詢某個索引的分片情況     

GET /_cat/indices?v    //查詢es中存在那些索引

PUT /movie_index    創建一個索引

DELETE /movie_index  洗掉一個索引,其實ES是不洗掉和修改任何資料的,只能其增加版本號

PUT /index/type/id    // 插入式各欄位的意思

GET movie_index/movie/1  直接用_id進行查詢

修改-全部欄位值替換  , 格式和新增一樣,需要將欄位全部寫出賦值

修改-某一欄位值替換:如下
POST movie_index/movie/3/_update
{
  "doc": {
    "doubanScore":"7.0"
  }
}

DELETE movie_index/movie/3   洗掉一個document

按條件查詢:如下
GET movie_index/movie/_search
{
  "query":{
    "match_all": {}
  }
}

按分詞查詢:如下
GET movie_index/movie/_search
{
  "query":{
    "match": {"name":"red"}
  }
}

按分詞子屬性查詢:
GET movie_index/movie/_search
{
  "query":{
    "match": {"actorList.name":"zhang"}
  }
}

按短語查詢,不再利用分詞技術,直接用短語在原始資料中匹配
GET movie_index/movie/_search
{
    "query":{
      "match_phrase": {"name":"operation red"}
    }
}

fuzzy查詢,無情精確匹配時,查詢出非常接近的詞
GET movie_index/movie/_search
{
    "query":{
      "fuzzy": {"name":"rad"}
    }
}

filter過濾查詢:查詢后過濾
GET movie_index/movie/_search
{
    "query":{
      "match": {"name":"red"}
    },
    "post_filter":{
      "term": {
        "actorList.id": 3
      }
    }
}

filter  :   查詢前過濾
GET movie_index/movie/_search
{
    "query":{
        "bool":{
          "filter":[ {"term": {  "actorList.id": "1"  }},
                     {"term": {  "actorList.id": "3"  }}
           ],
           "must":{"match":{"name":"red"}}
         }
    }
}


filter 按照范圍過濾:
GET movie_index/movie/_search
{
   "query": {
     "bool": {
       "filter": {
         "range": {
            "doubanScore": {"gte": 8}   // gt 大于   lt 小于  gte 大于等于  lte 小于等于
         }
       }
     }
   }
}

排序:
GET movie_index/movie/_search
{
  "query":{
    "match": {"name":"red sea"}
  }
  , "sort": [
    {
      "doubanScore": {
        "order": "desc"
      }
    }
  ]
}

分頁查詢:
GET movie_index/movie/_search
{
  "query": { "match_all": {} },
  "from": 1,
  "size": 1
}

指定查詢欄位:
GET movie_index/movie/_search
{
  "query": { "match_all": {} },
  "_source": ["name", "doubanScore"]
}

高亮顯示:
GET movie_index/movie/_search
{
    "query":{
      "match": {"name":"red sea"}
    },
    "highlight": {
      "fields": {"name":{} }
    }
}

聚合:
GET movie_index/movie/_search
{
  "aggs": {
    "groupby_actor": {
      "terms": {
        "field": "actorList.name.keyword"     // .keyword  使其不分詞
      }
    }
  }
}


字串匹配查詢
GET pv/_search
{
  "query": {
      "query_string": {
        "default_field": "name",
        "query": "076-97c8-24ca6147"
      }
  }
}
將會搜索name欄位包含076-97c8-24ca6147的資料記錄

es索引重建:
https://www.cnblogs.com/juncaoit/p/12815582.html
https://www.cnblogs.com/Ace-suiyuan008/p/9985249.html

11.中文分詞

https://github.com/medcl/elasticsearch-analysis-ik

12.動態同義詞(自定義)

https://github.com/bells/elasticsearch-analysis-dynamic-synonym/tree/master

13.JavaAPI(實作ES的工具類,采用了高級API)

(推薦下載下來看,有點多)
鏈接:https://github.com/MrXuSS/EsUtils
pom.xml

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.74</version>
</dependency>

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.9.2</version>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>

介面:

public interface EsClient {
    /**
     * 向es中創建檔案索引, 若es中已存在改index,則插入失敗,
     *
     * @param indexName 索引名稱
     * @param document  id
     * @param jsonStr   json字串, 要存入的資料
     */
    public Boolean insertIndexWithJsonStr(String indexName, String document, String jsonStr);

    /**
     * 查詢指定id下索引資料
     *
     * @param indexName 索引名稱
     * @param document  id
     * @return 回傳得到的字串, 沒有回傳null
     * {"age":18,"id":1,"name":"xuchenglei"}
     */
    public String queryIndex(String indexName, String document);

    /**
     * 查詢索引下的所有資料
     * @param indexName 索引名稱
     * @param startNum 開始的位置
     * @param pageSize 分頁的大小
     * @return 資料的字串, json格式; 沒有回傳null
     *  [{"name":"xuchenglei","id":1,"age":18},{"name":"xuchenglei","id":2,"age":18}]
     */
    public String queryIndex(String indexName, Integer startNum, Integer pageSize);

    /**
     * 根據索引名稱和id洗掉資料
     * @param indexName 索引名稱
     * @param document id
     * @return 是否洗掉成功; 索引不存在返貨false
     */
    public Boolean deleteIndex(String indexName, String document);

    /**
     * 洗掉indexName下的所有索引資料
     * @param indexName 索引名稱
     * @return 洗掉是否成功,
     */
    public Boolean deleteIndex(String indexName);

    /**
     * 判斷索引是否存在
     * @param indexName 索引名稱
     * @param document id
     * @return true or false
     */
    public Boolean isIndexExists(String indexName, String document);

    /**
     * 判斷索引是否存在
     * @param indexName 索引名稱
     * @return true or false
     */
    public Boolean isIndexExists(String indexName);

    /**
     * 查詢出所有的index
     * @return 查詢出所有的索引 Set<String>
     */
    public Set<String> queryAllIndex();

    /**
     * 根據 index 和 id 更新 索引資料
     * @param indexName 索引名稱
     * @param document id
     * @param jsonStr 要更新的json
     * @return 是否更新成功
     */
    public Boolean updateIndex(String indexName, String document, String jsonStr);

    /**
     * index下的搜索
     * @param field 屬性
     * @param text 值
     * @param indexName 索引名稱
     * @param startNum 開始的位置
     * @param pageSize 分頁的大小
     * @return 回傳符合條件的值
     */
    public String search(String field, String text, String indexName, Integer startNum, Integer pageSize);

    /**
     * 模糊查詢, 并實作高亮
     * @param field 屬性名
     * @param text value
     * @param indexName 索引名
     * @param startNum 開始的位置
     * @param pageSize 分頁大小
     * @return json
     */
    public String searchFuzzy(String field, String text, String indexName, Integer startNum, Integer pageSize);

    /**
     * 獲取當前索引下的資料量
     * @param indexName 索引名稱
     * @return 資料量條數
     */
    public Long searchTotalHitsNum(String indexName);

    /**
     * 向es中創建檔案索引, 若es中已存在改index,則插入失敗,(異步)
     *
     * @param indexName 索引名稱
     * @param document  id
     */
    public void insertIndexWithJsonStrAsync(String indexName, String document, String jsonStr);

    /**
     * 根據索引名稱和id洗掉資料,(異步)
     * @param indexName 索引名稱
     * @param document id
     */
    public void deleteIndexAsync(String indexName, String document);

    /**
     * 洗掉indexName下的所有索引資料,(異步)
     * @param indexName 索引名稱
     */
    public void deleteIndexAsync(String indexName);

    /**
     * 根據 index 和 id 更新 索引資料 (異步)
     * @param indexName 索引名稱
     * @param document id
     * @param jsonStr 要更新的json
     */
    public void updateIndexAsync(String indexName, String document, String jsonStr);

    /**
     * 索引重建(同步), 注意:目標索引需要提前創建好
     * @param fromIndex 重新索引的索引名
     * @param destIndex 重新索引后的索引名
     * @return 新創建的檔案數
     */
    public Long reIndex(String fromIndex, String destIndex);

    /**
     * 索引重建(異步),注意:目標索引需要提前創建好
     * @param fromIndex 重新索引的索引名
     * @param destIndex 重新索引后的索引名
     */
    public void reIndexAsync(String fromIndex, String destIndex);
}

實作單例模式:

/**
 * 以單例模式提供EsClient實體
 */
public class EsServerManager {
    private static EsServerManager instance;
    private static RestHighLevelClient client;
    private EsServerManager(){
        HttpHost host = new HttpHost("192.168.2.201", 9200, "http");
        client = new RestHighLevelClient(RestClient.builder(host));
    }
    public static synchronized EsServerManager getInstance(){
        if(instance == null){
            instance = new EsServerManager();
        }
        return instance;
    }
    public RestHighLevelClient getClient(){
        return client;
    }
}

API:

public class EsClientImpl implements EsClient{

    private static Log log = LogFactory.getLog(EsClientImpl.class);

    /**
     * 向es中創建檔案索引, 若es中已存在改index,則插入失敗,
     *
     * @param indexName 索引名稱
     * @param document  id
     * @param jsonStr   json字串, 要存入的資料
     */
    public Boolean insertIndexWithJsonStr(String indexName, String document, String jsonStr) {
        Boolean indexExists = isIndexExists(indexName, document);
        Boolean result = false;
        if (!indexExists) {
            IndexRequest indexRequest = new IndexRequest(indexName)
                    .id(document)
                    .source(jsonStr, XContentType.JSON);
            IndexResponse indexResponse = null;
            try {
                indexResponse = EsServerManager.getInstance().getClient().index(indexRequest, RequestOptions.DEFAULT);
                if(indexResponse.getResult() == DocWriteResponse.Result.CREATED){
                    result = true;
                }
                log.info(indexResponse.getIndex() + "--" + indexResponse.getId() + "--" + "插入成功");

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 查詢指定id下索引資料
     *
     * @param indexName 索引名稱
     * @param document  id
     * @return 回傳得到的字串, 沒有回傳null
     * {"age":18,"id":1,"name":"xuchenglei"}
     */
    public String queryIndex(String indexName, String document) {
        Boolean indexExists = isIndexExists(indexName, document);
        if (indexExists) {
            GetResponse getResponse = null;
            GetRequest getRequest = new GetRequest(indexName, document);
            try {
                getResponse = EsServerManager.getInstance().getClient().get(getRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return getResponse == null ? null : getResponse.getSourceAsString().toString();
        } else {
            return null;
        }
    }

    /**
     * 查詢索引下的所有資料
     * @param indexName 索引名稱
     * @return 資料的字串, json格式; 沒有回傳null
     *  [{"name":"xuchenglei","id":1,"age":18},{"name":"xuchenglei","id":2,"age":18}]
     */
    public String queryIndex(String indexName, Integer startNum, Integer pageSize){
        Boolean indexExists = isIndexExists(indexName);
        if (indexExists) {
            SearchResponse searchResponse = null;
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(indexName);
            searchSourceBuilder.from(startNum);
            searchSourceBuilder.size(pageSize);
            searchRequest.source(searchSourceBuilder);
            try {
                searchResponse = EsServerManager.getInstance().getClient().search(searchRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(searchResponse != null){
                SearchHit[] searchHits = searchResponse.getHits().getHits();
                List<Map<String, Object>> arrayListMap = new ArrayList<Map<String, Object>>();
                for (SearchHit searchHit : searchHits) {
                    Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
                    arrayListMap.add(sourceAsMap);
                }
                return JSON.toJSONString(arrayListMap);
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * 根據索引名稱和id洗掉資料
     * @param indexName 索引名稱
     * @param document id
     * @return 是否洗掉成功; 索引不存在返貨false
     */
    public Boolean deleteIndex(String indexName, String document){
        Boolean indexExists = isIndexExists(indexName, document);
        Boolean result = false;
        if(indexExists) {
            DeleteRequest deleteRequest = new DeleteRequest(indexName, document);
            DeleteResponse deleteResponse = null;
            try {
                deleteResponse = EsServerManager.getInstance().getClient().delete(deleteRequest, RequestOptions.DEFAULT);
               if(deleteResponse.getResult() == DocWriteResponse.Result.DELETED){
                    result = true;
               }
                log.info(deleteResponse.getIndex()+"--"+deleteResponse.getId()+":已洗掉");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 洗掉indexName下的所有索引資料
     * @param indexName 索引名稱
     * @return 洗掉是否成功,
     */
    public Boolean deleteIndex(String indexName){
        Boolean indexExists = isIndexExists(indexName);
        Boolean result = false;
        if(indexExists){
            DeleteIndexRequest deleteRequest = new DeleteIndexRequest(indexName);
            AcknowledgedResponse acknowledgedResponse = null;
            try {
                acknowledgedResponse = EsServerManager.getInstance().getClient().indices().delete(deleteRequest, RequestOptions.DEFAULT);
                if(acknowledgedResponse.isAcknowledged()){
                    result = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }

    /**
     * 判斷索引是否存在
     * @param indexName 索引名稱
     * @param document id
     * @return true or false
     */
    public Boolean isIndexExists(String indexName, String document){
        GetRequest getRequest = new GetRequest(indexName, document);
        // 禁用提取源
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        // 禁用提取存盤欄位
        getRequest.storedFields("_none_");

        Boolean exists = false;
        try {
            exists = EsServerManager.getInstance().getClient().exists(getRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return exists;
    }

    /**
     * 判斷索引是否存在
     * @param indexName 索引名稱
     * @return true or false
     */
    public Boolean isIndexExists(String indexName){
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        Boolean exists = false;
        try {
            exists = EsServerManager.getInstance().getClient().indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return exists;
    }

    /**
     * 查詢出所有的index
     * @return 查詢出所有的索引 Set<String>
     */
    public Set<String> queryAllIndex(){
        GetAliasesRequest getAliasesRequest = new GetAliasesRequest();
        Set<String> indexNameKeySet = new HashSet<String>();
        try {
            GetAliasesResponse getAliasesResponse = EsServerManager.getInstance().getClient().indices().getAlias(getAliasesRequest, RequestOptions.DEFAULT);
            Set<String> keySet = getAliasesResponse.getAliases().keySet();
            for (String s : keySet) {
                if(!s.startsWith(".")){
                    indexNameKeySet.add(s);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return indexNameKeySet;
    }

    /**
     * 根據 index 和 id 更新 索引資料
     * @param indexName 索引名稱
     * @param document id
     * @return 是否更新成功
     */
    public Boolean updateIndex(String indexName, String document, String jsonStr){
        Boolean indexExists = isIndexExists(indexName, document);
        Boolean result = false;
        if(indexExists){
            UpdateRequest updateRequest = new UpdateRequest(indexName, document).doc(jsonStr,XContentType.JSON);
            UpdateResponse updateResponse = null;
            try {
                updateResponse = EsServerManager.getInstance().getClient().update(updateRequest, RequestOptions.DEFAULT);
                if(updateResponse.getResult() == DocWriteResponse.Result.UPDATED){
                    result = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 全量匹配查詢
     * @param field 屬性
     * @param text 值
     * @param indexName 索引名稱
     * @param startNum 開始的位置
     * @param pageSize 分頁的大小
     * @return 回傳符合條件的值
     */
    public String search(String field, String text, String indexName, Integer startNum, Integer pageSize){
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(indexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        searchSourceBuilder.query(QueryBuilders.termQuery(field, text));

        searchSourceBuilder.from(startNum);
        searchSourceBuilder.size(pageSize);

        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            searchResponse = EsServerManager.getInstance().getClient().search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] searchHits = searchResponse.getHits().getHits();
            for (SearchHit hit : searchHits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                resultMapList.add(sourceAsMap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(resultMapList);
    }

    /**
     * 模糊查詢, 并實作高亮
     * @param field 屬性名
     * @param text value
     * @param indexName 索引名稱
     * @return json
     */
    public String searchFuzzy(String field, String text, String indexName, Integer startNum, Integer pageSize) {
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(indexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.wildcardQuery(field, "*"+text+"*"));
        searchSourceBuilder.from(startNum);
        searchSourceBuilder.size(pageSize);
        searchRequest.source(searchSourceBuilder);
        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field(field);
        highlightTitle.highlighterType("unified");
        highlightBuilder.field(highlightTitle);
        highlightBuilder.preTags("<span style=\"color:red\">");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        SearchResponse searchResponse = null;
        try {
            searchResponse = EsServerManager.getInstance().getClient().search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] searchHits = searchResponse.getHits().getHits();
            for (SearchHit hit : searchHits) {
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField highlightField = highlightFields.get(field);
                Text[] fragments = highlightField.fragments();
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                sourceAsMap.put(field, fragments[0].string());
                resultMapList.add(sourceAsMap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(resultMapList);
    }

    /**
     * 獲取當前索引下的資料量
     * @param indexName 索引名稱
     * @return 資料量條數
     */
    public Long searchTotalHitsNum(String indexName) {
        Boolean indexExists = isIndexExists(indexName);
        Long result = -1L;
        if(indexExists){
            SearchRequest searchRequest = new SearchRequest(indexName);
            SearchResponse searchResponse = null;
            try {
                searchResponse = EsServerManager.getInstance().getClient().search(searchRequest, RequestOptions.DEFAULT);
                result = searchResponse.getHits().getTotalHits().value;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向es中創建檔案索引, 若es中已存在改index,則插入失敗,(異步)
     *
     * @param indexName 索引名稱
     * @param document  id
     * @param jsonStr   json字串, 要存入的資料
     */
    public void insertIndexWithJsonStrAsync(String indexName, String document, String jsonStr) {
        Boolean indexExists = isIndexExists(indexName, document);
        if (!indexExists) {
            IndexRequest indexRequest = new IndexRequest(indexName)
                    .id(document)
                    .source(jsonStr, XContentType.JSON);
            ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
                public void onResponse(IndexResponse indexResponse) {
                    log.info("索引"+indexResponse.getIndex()+"--"+indexResponse.getId()+"插入成功");
                }

                public void onFailure(Exception e) {
                    e.printStackTrace();
                }
            };
            EsServerManager.getInstance().getClient().indexAsync(indexRequest, RequestOptions.DEFAULT, listener);
        }else{
            log.info("插入失敗"+"索引"+indexName+"--"+document+"--"+"已存在");
        }
    }

    /**
     * 根據索引名稱和id洗掉資料,(異步)
     * @param indexName 索引名稱
     * @param document id
     * @return 是否洗掉成功; 索引不存在返貨false
     */
    public void deleteIndexAsync(String indexName, String document) {
        Boolean indexExists = isIndexExists(indexName, document);
        if(indexExists) {
            final DeleteRequest deleteRequest = new DeleteRequest(indexName, document);
            ActionListener<DeleteResponse> listener = new ActionListener<DeleteResponse>() {
                public void onResponse(DeleteResponse deleteResponse) {
                    log.info(deleteResponse.getIndex() + "--" + deleteResponse.getId() + "已洗掉");
                }

                public void onFailure(Exception e) {
                    e.printStackTrace();
                }
            };
            EsServerManager.getInstance().getClient().deleteAsync(deleteRequest, RequestOptions.DEFAULT, listener);
        }else {
            log.info("索引"+indexName+"--"+document+"不存在");
        }
    }

    /**
     * 洗掉indexName下的所有索引資料,(異步)
     * @param indexName 索引名稱
     * @return 洗掉是否成功,
     */
    public void deleteIndexAsync(String indexName) {
        Boolean indexExists = isIndexExists(indexName);
        if(indexExists){
            final DeleteIndexRequest deleteRequest = new DeleteIndexRequest(indexName);
            ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
                public void onResponse(AcknowledgedResponse AcknowledgedResponse) {
                    log.info(AcknowledgedResponse.toString());
                }

                public void onFailure(Exception e) {
                    e.printStackTrace();
                }
            };
            EsServerManager.getInstance().getClient().indices().deleteAsync(deleteRequest, RequestOptions.DEFAULT, listener);
        }else {
            log.info("索引"+indexName+"不存在");
        }
    }

    /**
     * 根據 index 和 id 更新 索引資料 (異步)
     * @param indexName 索引名稱
     * @param document id
     * @param jsonStr 要更新的json
     * @return 是否更新成功
     */
    public void updateIndexAsync(String indexName, String document, String jsonStr) {
        Boolean indexExists = isIndexExists(indexName, document);
        if(indexExists) {
            final UpdateRequest updateRequest = new UpdateRequest(indexName, document).doc(jsonStr, XContentType.JSON);
            ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() {
                public void onResponse(UpdateResponse updateResponse) {
                    log.info("索引" + updateResponse.getIndex() + "--" + updateResponse.getId() + "更新成功");
                }

                public void onFailure(Exception e) {
                    e.printStackTrace();
                }
            };
            EsServerManager.getInstance().getClient().updateAsync(updateRequest, RequestOptions.DEFAULT, listener);
        }else {
            log.info("索引"+indexName+"--"+document+"不存在");
        }
    }

    /**
     * 索引重建(同步), 注意:目標索引需要提前創建好
     * @param fromIndex 重新索引的索引名
     * @param destIndex 重新索引后的索引名
     * @return 新創建的檔案數
     */
    public Long reIndex(String fromIndex, String destIndex) {
        Boolean fromIndexExists = isIndexExists(fromIndex);
        Boolean destIndexExists = isIndexExists(destIndex);
        Long result = 0L;
        if(fromIndexExists && destIndexExists){
            ReindexRequest reindexRequest = new ReindexRequest();
            reindexRequest.setSourceIndices(fromIndex);
            reindexRequest.setDestIndex(destIndex);
            reindexRequest.setSourceBatchSize(5000);
            reindexRequest.setSlices(5);
            BulkByScrollResponse reindexResponse = null;
            try {
                reindexResponse = EsServerManager.getInstance().getClient().reindex(reindexRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(reindexResponse != null) {
                result = reindexResponse.getCreated();
                log.info("時間:"+reindexResponse.getTook());
            }
        }else {
            if(!fromIndexExists){
                log.info("fromIndex不存在");
            }
            if(!destIndexExists){
                log.info("destIndex不存在");
            }
        }
        return result;
    }
    /**
     * 索引重建(異步), 注意:目標索引需要提前創建好
     * @param fromIndex 重新索引的索引名
     * @param destIndex 重新索引后的索引名
     */
    public void reIndexAsync(String fromIndex, String destIndex) {
        Boolean fromIndexExists = isIndexExists(fromIndex);
        Boolean destIndexExists = isIndexExists(destIndex);
        if(fromIndexExists && destIndexExists){
            ReindexRequest reindexRequest = new ReindexRequest();
            reindexRequest.setSourceIndices(fromIndex);
            reindexRequest.setDestIndex(destIndex);
            reindexRequest.setSourceBatchSize(1000);
            ActionListener<BulkByScrollResponse> actionListener = new ActionListener<BulkByScrollResponse>() {
                public void onResponse(BulkByScrollResponse bulkByScrollResponse) {
                    log.info("新創建的索引數" + bulkByScrollResponse.getCreated());
                    log.info("更新的索引數"+ bulkByScrollResponse.getUpdated());
                    log.info("時間:"+bulkByScrollResponse.getTook());
                }

                public void onFailure(Exception e) {
                    e.printStackTrace();
                }
            };
            EsServerManager.getInstance().getClient().reindexAsync(reindexRequest, RequestOptions.DEFAULT, actionListener);
        }else {
            if(!fromIndexExists){
                log.info("fromIndex不存在");
            }
            if(!destIndexExists){
                log.info("destIndex不存在");
            }
        }
    }
}

專案中也可以使用JestClient,支持這種JSON格式的查詢方式:
在官方的RestClient 基礎上,進行了簡單包裝的Jest客戶端,而且該客戶端也與springboot完美集成,

application.properties中加入
spring.elasticsearch.jest.uris=http://192.168.67.163:9200
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
   <groupId>io.searchbox</groupId>
   <artifactId>jest</artifactId>
   <version>5.3.3</version>
</dependency>


<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency>
   <groupId>net.java.dev.jna</groupId>
   <artifactId>jna</artifactId>
   <version>4.5.1</version>
</dependency>
@Autowired
JestClient jestClient;

@Test
public void testEs() throws IOException {
   String query="{\n" +
         "  \"query\": {\n" +
         "    \"match\": {\n" +
         "      \"actorList.name\": \"張譯\"\n" +
         "    }\n" +
         "  }\n" +
         "}";
   Search search = new Search.Builder(query).addIndex("movie_chn").addType("movie").build();

   SearchResult result = jestClient.execute(search);

   List<SearchResult.Hit<HashMap, Void>> hits = result.getHits(HashMap.class);

   for (SearchResult.Hit<HashMap, Void> hit : hits) {
      HashMap source = hit.source;
      System.err.println("source = " + source);
   }
}

總結

ElasticSearch作為搜索引擎,在很多的搜索場景下應用的比較廣泛,內容相對來說比較簡單,但是有點雜,參考目錄來看吧,

笨鳥先飛,熟能生巧 ~
本菜鳥QQ:599903582
比心心~

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/241980.html

標籤:其他

上一篇:前后端分離的若依(ruoyi)基本使用

下一篇:推薦系統的分類

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more