ES QUERY DSL

ES CURL

Posted by gomyck on July 15, 2022

Elasticsearch 查询语句采用基于 RESTful 风格的接口封装成 JSON 格式的对象,称之为 Query DSL。Elasticsearch 查询分类大致分为全文查询、词项查询、复合查询、嵌套查询、位置查询、特殊查询。

Elasticsearch 查询从机制分为两种,一种是根据用户输入的查询词,通过排序模型计算文档与查询词之间的相关度, 并根据评分高低排序返回;

另一种是过滤机制,只根据过滤条件对文档进行过滤,不计算评分,速度相对较快。

ES 新增索引操作

1

ES 标准查询模版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
GET map_location_online/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "@timestamp": {
              "gte": "2022-08-04T08:23:36"
            }
          }
        },
        {
          "match": {
            "plate_no": {
              "query": "XB00"
            }
          }
        }
      ],
      "filter": [
        {
          "geo_shape": {
            "location": {
              "shape": {
                "type": "circle",
                "radius": "100m",
                "coordinates": [
                    119.947350,
                    43.622627
                ]
              },
              "relation": "within"
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 20,
  "_source": ["plate_no", "location"],
  "highlight": {
    "fields": {
      "plate_no": {}
    }
  },
  "stored_fields": ["plate_no"],
  "version": true,
  "aggs": {
    "xxxxx": {
      "terms": {
        "field": "age"
      }
    }
  },
  "script_fields": {
    "xxx": {
      "script": {
        "lang": "painless",
        "inline": "doc['qce_id'].value * 2"
      }
    }
  }
}

全文查询

es 全文查询主要用于在全文字段上,主要考虑查询词与文档的相关性(Relevance)。

match

match query 用于搜索单个字段,首先会针对查询语句进行解析(经过 analyzer),主要是对查询语句进行分词,分词后查询语句的任何一个词项被匹配,文档就会被搜到,默认情况下相当于对分词后词项进行 or 匹配操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
GET article/_search
{
  "query": {
    "match": {
      "title": {
        "query": "Elasticsearch 查询优化"
      }
    }
  }
}

等同于 or 匹配操作,如下:

GET article/_search
{
  "query": {
    "match": {
      "title": {
        "query": "Elasticsearch 查询优化",
        "operator": "or"
      }
    }
  }
}

match_phrase

match_phrase query 首先会把 query 内容分词,分词器可以自定义,同时文档还要满足以下两个条件才会被搜索到:

分词后所有词项都要出现在该字段中(相当于 and 操作)。字段中的词项顺序要一致。

例如,有以下 3 个文档,使用 match_phrase 查询 “what a wonderful life”,只有前两个文档会被匹配:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
PUT test_idx/test_tp/1
{
  "desc": "what a wonderful life"
}

PUT test_idx/test_tp/2
{
  "desc": "what a life"
}

PUT test_idx/test_tp/3
{
  "desc": "life is what"
}

GET test_idx/test_tp/_search
{
  "query": {
    "match_phrase": {
      "desc": "what life"
    }
  }
}

match_phrase_prefix

match_phrase_prefix 和 match_phrase 类似,只不过 match_phrase_prefix 支持最后一个 term 的前缀匹配。

1
2
3
4
5
6
7
8
GET test_idx/test_tp/_search
{
  "query": {
    "match_phrase_prefix": {
      "desc": "what li"
    }
  }
}

multi_match

multi_match 是 match 的升级,用于搜索多个字段。查询语句为 “java 编程”,查询域为 title 和 description,查询语句如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
GET books/_search
{
  "query": {
    "multi_match": {
      "query": "java 编程",
      "fields": [
        "title",
        "description"
      ]
    }
  }
}

multi_match 支持对要搜索的字段的名称使用通配符,示例如下:

GET books/_search
{
  "query": {
    "multi_match": {
      "query": "java 编程",
      "fields": [
        "title",
        "*_name"
      ]
    }
  }
}

同时,也可以用指数符指定搜索字段的权重。指定关键词出现在 title 中的权重是出现在 description 字段中的 3 倍,命令如下:

GET books/_search
{
  "query": {
    "multi_match": {
      "query": "java 编程",
      "fields": [
        "title^3",
        "description"
      ]
    }
  }
}

common_terms

common_terms query 是一种在不牺牲性能的情况下替代停用词提高搜索准确率和召回率的方案。

查询中的每个词项都有一定的代价,以搜索 “The brown fox” 为例,query 会被解析成三个词项 “the”“brown” 和“fox”,每个词项都会到索引中执行一次查询。 很显然包含 “the” 的文档非常多,相比其他词项,“the”的重要性会低很多。传统的解决方案是把 “the” 当作停用词处理, 去除停用词之后可以减少索引大小,同时在搜索时减少对停用词的收缩。

虽然停用词对文档评分影响不大,但是当停用词仍然有重要意义的时候,去除停用词就不是完美的解决方案了。如果去除停用词, 就无法区分 “happy” 和“not happy”, “The”“To be or not to be”就不会在索引中存在,搜索的准确率和召回率就会降低。

common_terms query 提供了一种解决方案,它把 query 分词后的词项分成重要词项(低频词项)和不重要的词项(高频词,也就是之前的停用词)。 在搜索的时候,首先搜索和重要词项匹配的文档,这些文档是词项出现较少并且词项对其评分影响较大的文档。然后执行第二次查询,搜索对评分影响较小的高频词项, 但是不计算所有文档的评分,而是只计算第一次查询已经匹配的文档得分。如果一个查询中只包含高频词,那么会通过 and 连接符执行一个单独的查询,换言之, 会搜索所有的词项。

词项是高频词还是低频词是通过 cutoff frequency 来设置阀值的,取值可以是绝对频率(频率大于 1)或者相对频率(0~1)。common_terms query 最有趣之处在于它能自适应特定领域的停用词,例如,在视频托管网站上,诸如 “clip” 或“video”之类的高频词项将自动表现为停用词,无须保留手动列表。

例如,文档频率高于 0.1% 的词项将会被当作高频词项,词频之间可以用 low_freq_operator、high_freq_operator 参数连接。设置低频词操作符为 “and” 使所有的低频词都是必须搜索的,示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
GET books/_search
{
  "query": {
    "common": {
      "body": {
        "query": "nelly the elephant as a cartoon",
        "cutoff_frequency": 0.001,
        "low_freq_operator": "and"
      }
    }
  }
}


上述操作等价于:

GET books/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "body": "nelly"
          }
        },
        {
          "term": {
            "body": "elephant"
          }
        },
        {
          "term": {
            "body": "cartoon"
          }
        }
      ],
      "should": [
        {
          "term": {
            "body": "the"
          }
        },
        {
          "term": {
            "body": "as"
          }
        },
        {
          "term": {
            "body": "a"
          }
        }
      ]
    }
  }
}

query_string

query_string query 是与 Lucene 查询语句的语法结合非常紧密的一种查询,允许在一个查询语句中使用多个特殊条件关键字(如:AND OR NOT)对多个字段进行查询,建议熟悉 Lucene 查询语法的用户去使用。

simple_query_string

simple_query_string 是一种适合直接暴露给用户,并且具有非常完善的查询语法的查询语句,接受 Lucene 查询语法,解析过程中发生错误不会抛出异常。例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
GET books/_search
{
  "query": {
    "simple_query_string": {
      "query": "\"fried eggs\" +(eggplant | potato) -frittata",
      "analyzer": "snowball",
      "fields": [
        "body^5",
        "_all"
      ],
      "default_operator": "and"
    }
  }
}

词项查询

全文查询在执行查询之前会分析查询字符串,词项查询时对倒排索引中存储的词项进行精确匹配操作。词项级别的查询通常用于结构化数据,如数字、日期和枚举类型。

term

term 查询用来查找指定字段中包含给定单词的文档,term 查询不被解析,只有查询词和文档中的词精确匹配才会被搜索到,应用场景为查询人名、地名等需要精准匹配的需求。比如,查询 title 字段中含有关键词 “思想” 的书籍,查询命令如下:

1
2
3
4
5
6
7
8
GET books/_search
{
  "query": {
    "term": {
      "title": "思想"
    }
  }
}

避免 term 查询对 text 字段使用查询。

默认情况下,Elasticsearch 针对 text 字段的值进行解析分词,这会使查找 text 字段值的精确匹配变得困难。

要搜索 text 字段值,需改用 match 查询。

terms

terms 查询是 term 查询的升级,可以用来查询文档中包含多个词的文档。比如,想查询 title 字段中包含关键词 “java” 或 “python” 的文档,构造查询语句如下:

1
2
3
4
5
6
7
8
9
10
11
GET books/_search
{
  "query": {
    "terms": {
      "title": [
        "java",
        "python"
      ]
    }
  }
}

range

range query 即范围查询,用于匹配在某一范围内的数值型、日期类型或者字符串型字段的文档,比如搜索哪些书籍的价格在 50 到 100 之间、哪些书籍的出版时间在 2015 年到 2019 年之间。使用 range 查询只能查询一个字段,不能作用在多个字段上。

range 查询支持的参数有以下几种:

gt 大于,查询范围的最小值,也就是下界,但是不包含临界值。 gte 大于等于,和 gt 的区别在于包含临界值。 lt 小于,查询范围的最大值,也就是上界,但是不包含临界值。 lte 小于等于,和 lt 的区别在于包含临界值。

例如,想要查询价格大于 50,小于等于 70 的书籍,即 50 < price <= 70,构造查询语句如下:

1
2
3
4
5
6
7
8
9
10
11
GET bookes/_search
{
  "query": {
    "range": {
      "price": {
        "gt": 50,
        "lte": 70
      }
    }
  }
}

查询出版日期在 2015 年 1 月 1 日和 2019 年 12 月 31 之间的书籍,对 publish_time 字段进行范围查询,命令如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
GET bookes/_search
{
  "query": {
    "range": {
      "publish_ time": {
        "gte": "2015-01-01",
        "lte": "2019-12-31",
        "format": "yyyy-MM-dd"
      }
    }
  }
}

exists

exists 查询会返回字段中至少有一个非空值的文档。

1
2
3
4
5
6
7
8
GET bookes/_search
{
  "query": {
    "exists": {
      "field": "user"
    }
  }
}

以下文档会匹配上面的查询:

1
2
3
4
5
{ "user" : "jane" }             有 user 字段,且不为空。
{ "user" : "" }                 有 user 字段,值为空字符串。
{ "user" : "-" }                有 user 字段,值不为空。
{ "user" : [ "jane" ] }         有 user 字段,值不为空。
{ "user" : [ "jane", null ] }   有 user 字段,至少一个值不为空即可。

下面的文档都不会被匹配:

1
2
3
4
{ "user" : null }   虽然有 user 字段,但是值为空。
{ "user" : [] }     虽然有 user 字段,但是值为空。
{ "user" : [null] } 虽然有 user 字段,但是值为空。
{ "foo" : "bar" }   没有 user 字段。

prefix

prefix 查询用于查询某个字段中以给定前缀开始的文档,比如查询 title 中含有以 java 为前缀的关键词的文档,那么含有 java、javascript、javaee 等所有以 java 开头关键词的文档都会被匹配。查询 description 字段中包含有以 win 为前缀的关键词的文档,查询语句如下:

1
2
3
4
5
6
7
8
GET books/_search
{
  "query": {
    "prefix": {
      "description": "win"
    }
  }
}

wildcard

wildcard query 中文译为通配符查询,支持单字符通配符和多字符通配符,? 用来匹配一个任意字符,* 用来匹配零个或者多个字符。

以 H?tland 为例,Hatland、Hbtland 等都可以匹配,但是不能匹配 Htland,? 只能代表一位。H*tland 可以匹配 Htland、Habctland 等, * 可以代表 0 至多个字符。和 prefix 查询一样,wildcard 查询的查询性能也不是很高,需要消耗较多的 CPU 资源。

下面举一个 wildcard 查询的例子,假设需要找某一作者写的书,但是忘记了作者名字的全称,只记住了前两个字,那么就可以使用通配符查询,查询语句如下:

1
2
3
4
5
6
7
8
GET books/_search
{
  "query": {
    "wildcard": {
      "author": "哈哈*"
    }
  }
}

regexp

Elasticsearch 也支持正则表达式查询,通过 regexp query 可以查询指定字段包含与指定正则表达式匹配的文档。可以代表任意字符, “a.c.e” 和 “ab…” 都可以匹配 “abcde”,a{3}b{3}、a{2,3}b{2,4}、a{2,}{2,} 都可以匹配字符串 “aaabbb”。

例如需要匹配以 W 开头紧跟着数字的邮政编码,使用正则表达式查询构造查询语句如下:

1
2
3
4
5
6
7
8
GET books/_search
{
  "query": {
    "regexp": {
      "postcode": "W[0-9].+"
    }
  }
}

fuzzy

编辑距离又称 Levenshtein 距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。fuzzy 查询就是通过计算词项与文档的编辑距离来得到结果的,但是使用 fuzzy 查询需要消耗的资源比较大,查询效率不高,适用于需要模糊查询的场景。举例如下,用户在输入查询关键词时不小心把 “javascript” 拼成 “javascritp”,在存在拼写错误的情况下使用模糊查询仍然可以搜索到含有 “javascript” 的文档,查询语句如下:

1
2
3
4
5
6
7
8
9
GET books/_search
{
  "query": {
    "fuzzy": {
      "title": "javascritp"
    }
  }
}

type

type query 用于查询具有指定类型的文档。例如查询 Elasticsearch 中 type 为 computer 的文档,查询语句如下:

1
2
3
4
5
6
7
8
GET books/_search
{
  "query": {
    "type": {
      "value": "computer"
    }
  }
}

ids

ids query 用于查询具有指定 id 的文档。类型是可选的,也可以省略,也可以接受一个数组。如果未指定任何类型,则会查询索引中的所有类型。例如,查询类型为 computer,id 为 1、3、5 的文档,本质上是对文档 _id 的查询,所以对应的 value 是字符串类型,查询语句如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
GET books/_search
{
  "query": {
    "ids": {
      "type": "computer",
      "values": [
        "1",
        "3",
        "5"
      ]
    }
  }
}

复合查询

复合查询就是把一些简单查询组合在一起实现更复杂的查询需求,除此之外,复合查询还可以控制另外一个查询的行为。

bool

bool 查询可以把任意多个简单查询组合在一起,使用 must、should、must_not、filter 选项来表示简单查询之间的逻辑,每个选项都可以出现 0 次到多次,它们的含义如下:

must 文档必须匹配 must 选项下的查询条件,相当于逻辑运算的 AND,且参与文档相关度的评分。

should 文档可以匹配 should 选项下的查询条件也可以不匹配,相当于逻辑运算的 OR,且参与文档相关度的评分。

must_not 与 must 相反,匹配该选项下的查询条件的文档不会被返回;需要注意的是,must_not 语句不会影响评分,它的作用只是将不相关的文档排除。

filter 和 must 一样,匹配 filter 选项下的查询条件的文档才会被返回,但是 filter 不评分,只起到过滤功能,与 must_not 相反。

假设要查询 title 中包含关键词 java,并且 price 不能高于 70,description 可以包含也可以不包含虚拟机的书籍,构造 bool 查询语句如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
GET books/_search
{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "status": 1
        }
      },
      "must_not": {
        "range": {
          "price": {
            "gte": 70
          }
        }
      },
      "must": {
        "match": {
          "title": "java"
        }
      },
      "should": [
        {
          "match": {
            "description": "虚拟机"
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

boosting

boosting 查询用于需要对两个查询的评分进行调整的场景,boosting 查询会把两个查询封装在一起并降低其中一个查询的评分。

boosting 查询包括 positive、negative 和 negative_boost 三个部分,positive 中的查询评分保持不变,negative 中的查询会降低文档评分,negative_boost 指明 negative 中降低的权值。如果我们想对 2015 年之前出版的书降低评分,可以构造一个 boosting 查询,查询语句如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
GET books/_search
{
  "query": {
    "boosting": {
      "positive": {
        "match": {
          "title": "python"
        }
      },
      "negative": {
        "range": {
          "publish_time": {
            "lte": "2015-01-01"
          }
        }
      },
      "negative_boost": 0.2
    }
  }
}

boosting 查询中指定了抑制因子为 0.2,publish_time 的值在 2015-01-01 之后的文档得分不变,publish_time 的值在 2015-01-01 之前的文档得分为原得分的 0.2 倍。

constant_score

constant_score query 包装一个 filter query,并返回匹配过滤器查询条件的文档,且它们的相关性评分都等于 boost 参数值(可以理解为原有的基于 tf-idf 或 bm25 的相关分固定为 1.0,所以最终评分为 1.0 * boost,即等于 boost 参数值)。下面的查询语句会返回 title 字段中含有关键词 elasticsearch 的文档,所有文档的评分都是 1.8:

1
2
3
4
5
6
7
8
9
10
11
12
13
GET books/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "term": {
          "title": "elasticsearch"
        }
      },
      "boost": 1.8
    }
  }
}

dis_max

dis_max query 与 bool query 有一定联系也有一定区别,dis_max query 支持多并发查询,可返回与任意查询条件子句匹配的任何文档类型。与 bool 查询可以将所有匹配查询的分数相结合使用的方式不同,dis_max 查询只使用最佳匹配查询条件的分数。请看下面的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
GET books/_search
{
  "query": {
    "dis_max": {
      "tie_breaker": 0.7,
      "boost": 1.2,
      "queries": [
        {
          "term": {
            "age": 34
          }
        },
        {
          "term": {
            "age": 35
          }
        }
      ]
    }
  }
}

function_score

function_score query 可以修改查询的文档得分,这个查询在有些情况下非常有用,比如通过评分函数计算文档得分代价较高,可以改用过滤器加自定义评分函数的方式来取代传统的评分方式。

使用 function_score query,用户需要定义一个查询和一至多个评分函数,评分函数会对查询到的每个文档分别计算得分。

下面这条查询语句会返回 books 索引中的所有文档,文档的最大得分为 5,每个文档的得分随机生成,权重的计算模式为相乘模式。

1
2
3
4
5
6
7
8
9
10
11
12
13
GET books/_search
{
  "query": {
    "function_score": {
      "query": {
        "match all": {}
      },
      "boost": "5",
      "random_score": {},
      "boost_mode": "multiply"
    }
  }
}

使用脚本自定义评分公式,这里把 price 值的十分之一开方作为每个文档的得分,查询语句如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
GET books/_search
{
  "query": {
    "function_score": {
      "query": {
        "match": {
          "title": "java"
        }
      },
      "script_score": {
        "inline": "Math.sqrt(doc['price'].value/10)"
      }
    }
  }
}

indices

indices query 适用于需要在多个索引之间进行查询的场景,它允许指定一个索引名字列表和内部查询。indices query 中有 query 和 no_match_query 两部分,query 中用于搜索指定索引列表中的文档,no_match_query 中的查询条件用于搜索指定索引列表之外的文档。下面的查询语句实现了搜索索引 books、books2 中 title 字段包含关键字 javascript,其他索引中 title 字段包含 basketball 的文档,查询语句如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
GET books/_search
{
  "query": {
    "indices": {
      "indices": [
        "books",
        "books2"
      ],
      "query": {
        "match": {
          "title": "javascript"
        }
      },
      "no_match_query": {
        "term": {
          "title": "basketball"
        }
      }
    }
  }
}

嵌套查询

在 Elasticsearch 这样的分布式系统中执行全 SQL 风格的连接查询代价昂贵,是不可行的。相应地,为了实现水平规模地扩展,Elasticsearch 提供了以下两种形式的 join:

nested (嵌套查询)

文档中可能包含嵌套类型的字段,这些字段用来索引一些数组对象,每个对象都可以作为一条独立的文档被查询出来。

has_child (有子查询)和 has_parent (有父查询)

父子关系可以存在单个的索引的两个类型的文档之间。has_child 查询将返回其子文档能满足特定查询的父文档,而 has_parent 则返回其父文档能满足特定查询的子文档。

1
2
3
4
5
6
7
8
9
10
11
12
PUT /my_index
{
  "mappings": {
    "type1": {
      "properties": {
        "obj1": {
          "type": "nested"
        }
      }
    }
  }
}

has_child

文档的父子关系创建索引时在映射中声明,这里以员工(employee)和工作城市(branch)为例,它们属于不同的类型,相当于数据库中的两张表,如果想把员工和他们工作的城市关联起来,需要告诉 Elasticsearch 文档之间的父子关系,这里 employee 是 child type,branch 是 parent type,在映射中声明,执行命令:

1
2
3
4
5
6
7
8
9
10
11
PUT /company
{
  "mappings": {
    "branch": {},
    "employee": {
      "parent": {
        "type": "branch"
      }
    }
  }
}

使用 bulk api 索引 branch 类型下的文档,命令如下:

1
2
3
4
5
6
7
POST company/branch/_bulk
{"index":{"_id":"london"}}
{"name":"London Westminster","city":"London","country":"UK"}
{"index":{"_id":"liverpool"}}
{"name":"Liverpool Central","city":"Liverpool","country":"UK"}
{"index":{"_id":"paris"}}
{"name":"Champs Elysees","city":"Paris","country":"France"}

添加员工数据:

1
2
3
4
5
6
7
8
9
POST company/employee/_bulk
{ "index": { "_id": 1,"parent":"london" }}
{ "name": "Alice Smith","dob": "1970-10-24","hobby": "hiking" }
{ "index": { "_id": 2,"parent":"london" }}
{ "name": "Mark Tomas","dob": "1982-05-16","hobby": "diving" }
{ "index": { "_id": 3,"parent":"liverpool" }}
{ "name": "Barry Smith","dob": "1979-04-01","hobby": "hiking" }
{ "index": { "_id": 4,"parent":"paris" }}
{ "name": "Adrien Grand","dob": "1987-05-11","hobby": "horses" }

通过子文档查询父文档要使用 has_child 查询。例如,搜索 1980 年以后出生的员工所在的分支机构,employee 中 1980 年以后出生的有 Mark Thomas 和 Adrien Grand,他们分别在 london 和 paris,执行以下查询命令进行验证:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
GET company/branch/_search
{
  "query": {
    "has_child": {
      "type": "employee",
      "query": {
        "range": {
          "dob": {
            "gte": "1980-01-01"
          }
        }
      }
    }
  }
}

搜索哪些机构中有名为 “Alice Smith” 的员工,因为使用 match 查询,会解析为 “Alice” 和 “Smith”,所以 Alice Smith 和 Barry Smith 所在的机构会被匹配,执行以下查询命令进行验证:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
GET company/branch/_search
{
  "query": {
    "has_child": {
      "type": "employee",
      "score_mode": "max",
      "query": {
        "match": {
          "name": "Alice Smith"
        }
      }
    }
  }
}

可以使用 min_children 指定子文档的最小个数。例如,搜索最少含有两个 employee 的机构,查询命令如下:

1
2
3
4
5
6
7
8
9
10
11
12
GET company/branch/_search?pretty
{
  "query": {
    "has_child": {
      "type": "employee",
      "min_children": 2,
      "query": {
        "match_all": {}
      }
    }
  }
}

has_parent

通过父文档查询子文档使用 has_parent 查询。比如,搜索哪些 employee 工作在 UK,查询命令如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
GET company/employee/_search
{
  "query": {
    "has_parent": {
      "parent_type": "branch",
      "query": {
        "match": {
          "country": "UK"
        }
      }
    }
  }
}

位置查询

Elasticsearch 可以对地理位置点 geo_point 类型和地理位置形状 geo_shape 类型的数据进行搜索。为了学习方便,这里准备一些城市的地理坐标作为测试数据,每一条文档都包含城市名称和地理坐标这两个字段,这里的坐标点取的是各个城市中心的一个位置。首先把下面的内容保存到 geo.json 文件中:

1
2
3
4
5
6
7
8
9
10
11
12
{"index":{ "_index":"geo","_type":"city","_id":"1" }}
{"name":"北京","location":"39.9088145109,116.3973999023"}
{"index":{ "_index":"geo","_type":"city","_id": "2" }}
{"name":"乌鲁木齐","location":"43.8266300000,87.6168800000"}
{"index":{ "_index":"geo","_type":"city","_id":"3" }}
{"name":"西安","location":"34.3412700000,108.9398400000"}
{"index":{ "_index":"geo","_type":"city","_id":"4" }}
{"name":"郑州","location":"34.7447157466,113.6587142944"}
{"index":{ "_index":"geo","_type":"city","_id":"5" }}
{"name":"杭州","location":"30.2294080260,120.1492309570"}
{"index":{ "_index":"geo","_type":"city","_id":"6" }}
{"name":"济南","location":"36.6518400000,117.1200900000"}

创建一个索引并设置映射:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
PUT geo
{
  "mappings": {
    "city": {
      "properties": {
        "name": {
          "type": "keyword"
        },
        "location": {
          "type": "geo_point"
        }
      }
    }
  }
}

然后执行批量导入命令:

curl -XPOST “http://localhost:9200/_bulk?pretty” –data-binary @geo.json

geo_distance

geo_distance query 可以查找在一个中心点指定范围内的地理点文档。例如,查找距离天津 200km 以内的城市,搜索结果中会返回北京,命令如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
GET geo/_search
{
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "geo_distance": {
          "distance": "200km",
          "location": {
            "lat": 39.0851,
            "lon": 117.19937
          }
        }
      }
    }
  }
}

按各城市离北京的距离排序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
GET geo/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "_geo_distance": {
        "location": "39.9088145109,116.3973999023",
        "unit": "km",
        "order": "asc",
        "distance_type": "plane"
      }
    }
  ]
}

其中 location 对应的经纬度字段;unit 为 km 表示将距离以 km 为单位写入到每个返回结果的 sort 键中;distance_type 为 plane 表示使用快速但精度略差的 plane 计算方式。

geo_bounding_box

geo_bounding_box query 用于查找落入指定的矩形内的地理坐标。查询中由两个点确定一个矩形,然后在矩形区域内查询匹配的文档。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
GET geo/_search
{
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "geo_bounding_box": {
          "location": {
            "top_left": {
              "lat": 38.48644,
              "lon": 106.23248
            },
            "bottom_right": {
              "lat": 28.68202,
              "lon": 115.85794
            }
          }
        }
      }
    }
  }
}

geo_polygon

geo_polygon query 用于查找在指定多边形内的地理点。例如,呼和浩特、重庆、上海三地组成一个三角形,查询位置在该三角形区域内的城市,命令如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
GET geo/_search
{
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      }
    },
    "filter": {
      "geo_polygon": {
        "location": {
          "points": [
            {
              "lat": 40.84149,
              "lon": 111.75199
            },
            {
              "lat": 29.56471,
              "lon": 106.55073
            },
            {
              "lat": 31.23037,
              "lon": 121.4737
            }
          ]
        }
      }
    }
  }
}

geo_shape

geo_shape query 用于查询 geo_shape 类型的地理数据,地理形状之间的关系有相交、包含、不相交三种。创建一个新的索引用于测试,其中 location 字段的类型设为 geo_shape 类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PUT geoshape
{
  "mappings": {
    "city": {
      "properties": {
        "name": {
          "type": "keyword"
        },
        "location": {
          "type": "geo_shape"
        }
      }
    }
  }
}

关于经纬度的顺序这里做一个说明,geo_point 类型的字段纬度在前经度在后,但是对于 geo_shape 类型中的点,是经度在前纬度在后,这一点需要特别注意。

把西安和郑州连成的线写入索引:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
POST geoshape/city/1
{
  "name": "西安-郑州",
  "location": {
    "type": "linestring",
    "coordinates": [
      [
        108.93984,
        34.34127
      ],
      [
        113.6587142944,
        34.7447157466
      ]
    ]
  }
}

查询包含在由银川和南昌作为对角线上的点组成的矩形的地理形状,由于西安和郑州组成的直线落在该矩形区域内,因此可以被查询到。命令如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
GET geoshape/_search
{
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "geo_shape": {
          "location": {
            "shape": {
              "type": "envelope",
              "coordinates": [
                [
                  106.23248,
                  38.48644
                ],
                [
                  115.85794,
                  28.68202
                ]
              ]
            },
            "relation": "within"
          }
        }
      }
    }
  }
}

特殊查询

more_like_this

more_like_this query 可以查询和提供文本类似的文档,通常用于近似文本的推荐等场景。查询命令如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
GET books/_search
{
  "query": {
    "more_like_ this": {
      "fields": [
        "title",
        "description"
      ],
      "like": "java virtual machine",
      "min_term_freq": 1,
      "max_query_terms": 12
    }
  }
}

可选的参数及取值说明如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fields 要匹配的字段,默认是 _all 字段。
like 要匹配的文本。
min_term_freq 文档中词项的最低频率,默认是 2,低于此频率的文档会被忽略。
max_query_terms query 中能包含的最大词项数目,默认为 25。
min_doc_freq 最小的文档频率,默认为 5。
max_doc_freq 最大文档频率。
min_word length 单词的最小长度。
max_word length 单词的最大长度。
stop_words 停用词列表。
analyzer 分词器。
minimum_should_match 文档应匹配的最小词项数,默认为 query 分词后词项数的 30%。
boost terms 词项的权重。
include 是否把输入文档作为结果返回。
boost 整个 query 的权重,默认为 1.0。

script

Elasticsearch 支持使用脚本进行查询。例如,查询价格大于 180 的文档,命令如下:

1
2
3
4
5
6
7
8
9
10
11
GET books/_search
{
  "query": {
    "script": {
      "script": {
        "inline": "doc['price'].value > 180",
        "lang": "painless"
      }
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
以下是ES中一些常见的内置变量:

_source:代表当前文档的源文档,即原始JSON文档。您可以使用它来访问文档中的任何字段。

_score:代表当前文档的匹配得分,它是基于查询条件计算出来的。

doc:代表当前文档。您可以使用它来访问文档中的任何字段。例如,doc['field_name'].value。

params:代表在查询中传递的任何参数。您可以使用它来访问和使用传递的参数。

ctx:代表当前执行的上下文。它包含了很多有用的信息,例如当前日期、当前用户等。

now:代表当前日期和时间。您可以使用它来执行与日期和时间相关的计算。

Math:代表JavaScript中的Math对象,您可以使用它来执行各种数学运算。

emit():用于聚合查询中的map-reduce操作,可以将键值对发送到reduce函数中。

percolate

一般情况下,我们是先把文档写入到 Elasticsearch 中,通过查询语句对文档进行搜索。percolate query 则是反其道而行之的做法, 它会先注册查询条件,根据文档来查询 query。例如,在 my-index 索引中有一个 laptop 类型,文档有 price 和 name 两个字段, 在映射中声明一个 percolator 类型的 query,命令如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
PUT my-index
{
  "mappings": {
    "laptop": {
      "properties": {
        "price": {
          "type": "long"
        },
        "name": {
          "type": "text"
        }
      },
      "queries": {
        "properties": {
          "query": {
            "type": "percolator"
          }
        }
      }
    }
  }
}

注册一个 bool query,bool query 中包含一个 range query,要求 price 字段的取值小于等于 10000,并且 name 字段中含有关键词 macbook:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
PUT /my-index/queries/1?refresh
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "price": {
              "lte": 10000
            }
          }
        },
        {
          "match": {
            "name": "macbook"
          }
        }
      ]
    }
  }
}

通过文档查询 query:

1
2
3
4
5
6
7
8
9
10
11
12
13
GET /my-index/_search
{
  "query": {
    "percolate": {
      "field": "query",
      "document_type": "laptop",
      "document": {
        "price": 9999,
        "name": "macbook pro on sale"
      }
    }
  }
}

文档符合 query 中的条件,返回结果中可以查到上文中注册的 bool query。percolate query 的这种特性适用于数据分类、数据路由、事件监控和预警等场景。

其他知识点

stored_fields

1
2
3
4
5
6
7
8
9
10
11
12
13
14
不管将store设置为ture or false, elasticsearch都将为我们存储这些field, 不同的是:

当store为false时(默认配置),这些field只存储在"_source" field中。
当store为true时,这些field的value会存储在一个跟 _source 平级的独立的field中。同时也会存储在_source中,所以有两份拷贝。
那么什么情况下需要设置store field呢?一般情况有两种情况:

_source field在索引的mapping 中disable了。
这种情况下,如果不将某个field定义成store=true,那些将无法在返回的查询结果中看到这个field。

_source的内容非常大。
这时候如果我们想要在返回的_source document中解释出某个field的值的话,开销会很大(当然你也可以定义source filtering将减少network overhead),
比如某个document中保存的是一本书,所以document中可能有这些field: title, date, content。假如我们只是想查询书的title 跟date信息,
而不需要解释整个_source(非常大),这个时候我们可以考虑将title, date这些field设置成store=true。