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
          }
        }
      }
    }
  }
}

 

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