ElasticSearch7.6學習日記之ElasticSearch入門:開始搜索

開始搜索

將一些數據存儲到Elasticsearch索引後,您可以通過將請求發送到_search端點來對其進行搜索。要訪問全套搜索功能,請使用Elasticsearch Query DSL在請求正文中指定搜索條件。您可以在請求URI中指定要搜索的索引的名稱。

例如,以下請求檢索bank 索引中的所有文檔並按帳號排序:

GET /bank/_search
{
  "query": { "match_all": {} },
  "sort": [
    { "account_number": "asc" }
  ]
}

默認情況下,hits響應部分包含與搜索條件匹配的前10個文檔:

{
  "took" : 63,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
        "value": 1000,
        "relation": "eq"
    },
    "max_score" : null,
    "hits" : [ {
      "_index" : "bank",
      "_type" : "_doc",
      "_id" : "0",
      "sort": [0],
      "_score" : null,
      "_source" : {"account_number":0,"balance":16623,"firstname":"Bradshaw","lastname":"Mckenzie","age":29,"gender":"F","address":"244 Columbus Place","employer":"Euron","email":"[email protected]","city":"Hobucken","state":"CO"}
    }, {
      "_index" : "bank",
      "_type" : "_doc",
      "_id" : "1",
      "sort": [1],
      "_score" : null,
      "_source" : {"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"[email protected]","city":"Brogan","state":"IL"}
    }, ...
    ]
  }
}

該響應還提供有關搜索請求的以下信息:

  • took – Elasticsearch運行查詢多長時間(以毫秒爲單位)
  • timed_out –搜索請求是否超時
  • _shards –搜索了多少個分片以及成功,失敗或跳過了多少個分片。
  • max_score –找到的最相關文件的分數
  • hits.total.value -找到了多少個匹配的文檔
  • hits.sort -文檔的排序位置(不按相關性得分排序時)
  • hits._score-文檔的相關性得分(使用時不適用match_all

每個搜索請求都是獨立的:Elasticsearch在請求中不維護任何狀態信息。要翻閱搜索結果,請在您的請求中指定fromsize參數。

例如,以下請求的匹配數爲10到19:

GET /bank/_search
{
  "query": { "match_all": {} },
  "sort": [
    { "account_number": "asc" }
  ],
  "from": 10,
  "size": 10
}

既然您已經瞭解瞭如何提交基本的搜索請求,則可以開始構建比有趣的查詢match_all

要在字段中搜索特定術語,可以使用match查詢。例如,以下請求搜索address字段查找地址中包含關鍵詞milllane

GET /bank/_search
{
  "query": { "match": { "address": "mill lane" } }
}

要執行詞組搜索而不是匹配單個詞,請使用 match_phrase代替match。例如,以下請求僅匹配地址中包含短語mill lane

GET /bank/_search
{
  "query": { "match_phrase": { "address": "mill lane" } }
}

要構造更復雜的查詢,可以使用bool查詢來組合多個查詢條件。您可以根據需要(必須匹配),期望(應該匹配)或不期望(必須不匹配)指定條件。

例如,以下請求在bank索引中搜索屬於40歲客戶的帳戶,但不包括居住在愛達荷州(ID)的所有人:

GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "age": "40" } }
      ],
      "must_not": [
        { "match": { "state": "ID" } }
      ]
    }
  }
}

布爾查詢中的每個mustshouldmust_not元素稱爲查詢子句。文檔滿足每個條款must或 should條款的標準的程度有助於文檔的相關性得分。分數越高,文檔就越符合您的搜索條件。默認情況下,Elasticsearch返回按這些相關性分數排名的文檔。

must_not子句中的條件被視爲過濾器。它會影響文檔是否包含在結果中,但不會影響文檔的評分方式。您還可以顯式指定任意過濾器,以基於結構化數據包括或排除文檔。

例如,以下請求使用範圍過濾器將結果限制爲餘額在20,000美元到30,000美元(含)之間的帳戶。

GET /bank/_search
{
  "query": {
    "bool": {
      "must": { "match_all": {} },
      "filter": {
        "range": {
          "balance": {
            "gte": 20000,
            "lte": 30000
          }
        }
      }
    }
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章