专业的编程技术博客社区

网站首页 > 博客文章 正文

elasticsearch - DSL(elasticsearch菜鸟教程)

baijin 2024-10-24 08:46:12 博客文章 10 ℃ 0 评论

ES - Query DSL (Domain Specific Language)

ES提供了一套基于JSON完整的DSL(特定域语言)来定义查询。由 `叶子查询子句` 及 `复合查询子句` 两种类型子句组成抽象树查询(AST)。

概念相关

  • 相关性得分 - Relevance Scores

默认情况下,ES按照相关性得分对匹配的结果进行排序,来衡量每个文档与查询的匹配度. 在 `search api` 的元数据`_score`进行返回

  • 查询上下文 - Query Context

主要关注文档与查询子句的匹配程度如何

  • 过滤器上下文 - Filter Context

过滤上下文只返回是否匹配到相应文档

GET /_search
{
  "query": { 
    "bool": { 
      "must": [
        { "match": { "title":   "Search"        }},
        { "match": { "content": "Elasticsearch" }}
      ],
      "filter": [ 
        { "term":  { "status": "published" }},
        { "range": { "publish_date": { "gte": "2015-01-01" }}}
      ]
    }
  }
}

复合查询 - Compound Query

复合查询包装了其它复查询以及叶子查询,以组合其结果和分数,更改其行为或者从查询切换到过滤上下文。有`bool query` `boosting query` `contant_socre query` `dis_max query` `function_score query `

* [bool query](https://www.elastic.co/guide/en/elasticsearch/reference/7.x/query-dsl-bool-query.html#bool-min-should-match)

查询类型

  • must 子句(查询)必须出现在匹配的文档中,并将有助于得分
  • filter 必须出现在匹配的文档中。filter子句在过滤上下文中执行,_score会被忽略,并且子句会被缓存
  • should 子句应该出现在匹配中。注意与`minimum_should_match`参数使用
  • must_not 不必在匹配中出现。

示例如下:

POST _search
{
  "query": {
    "bool" : {
      "must" : {
        "term" : { "user.id" : "kimchy" }
      },
      "filter": {
        "term" : { "tags" : "production" }
      },
      "must_not" : {
        "range" : {
          "age" : { "gte" : 10, "lte" : 20 }
        }
      },
      "should" : [
        { "term" : { "tags" : "env1" } },
        { "term" : { "tags" : "deployed" } }
      ],
      "minimum_should_match" : 1,
      "boost" : 1.0
    }
  }
}
  • minimum_should_match

使用minimum_should_match参数指定返回的文档必须匹配的应当子句的数量或百分比。

Term-Level Query

根据结构化数据中的精确值进行查询

* exists - 检查文档中字段是否存在

* fuzzy - 模糊匹配

* ids query - 按照文档id查询


GET /_search
{
  "query": {
    "ids" : {
      "values" : ["1", "4", "100"]
    }
  }
}

* prefix query - 返回在提供的字段中包含特定前缀的文档

* range query - 区间查询

区间查询时有 `lt`, `lte` , `gt`, `gte`, `format`, relation, `time_zone`, `boost` 等参数

GET /_search
{
  "query": {
    "range": {
      "timestamp": {
        "gte": "now-1d/d",
        "lt": "now/d"
      }
    }
  }

* regexp query - 正则匹配查询

* term query - 精确值查询

* terms query - 多值查询

* terms_set query - 返回提供的字段中包含最少数目的精确文档

* type query

* wildcard query

term 查询时有些较长的字符串不一定能够匹配得上,可以用 [match_phase](https://www.elastic.co/guide/en/elasticsearch/reference/7.x/query-dsl-match-query-phrase.html) - 查询将分析文本,并从分析的文本中创建短语查询

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表