术语集查询
通过术语集查询,您可以在指定字段中搜索与最少数量的精确术语匹配的文档。terms_set
查询类似于 terms
查询,不同之处在于您可以指定返回文档所需匹配术语的最小数量。您可以将此数量指定在索引中的字段中,或者通过脚本指定。
例如,假设一个索引包含学生姓名和他们所上的课程。在为该索引设置映射时,您需要提供一个数值字段,该字段指定返回文档所需匹配术语的最小数量。
PUT students
{
"mappings": {
"properties": {
"name": {
"type": "keyword"
},
"classes": {
"type": "keyword"
},
"min_required": {
"type": "integer"
}
}
}
}
接下来,索引两个与学生对应的文档
PUT students/_doc/1
{
"name": "Mary Major",
"classes": [ "CS101", "CS102", "MATH101" ],
"min_required": 2
}
PUT students/_doc/2
{
"name": "John Doe",
"classes": [ "CS101", "MATH101", "ENG101" ],
"min_required": 2
}
现在搜索至少上过以下两门课程的学生:CS101
、CS102
、MATH101
GET students/_search
{
"query": {
"terms_set": {
"classes": {
"terms": [ "CS101", "CS102", "MATH101" ],
"minimum_should_match_field": "min_required"
}
}
}
}
响应包含这两个文档
{
"took" : 44,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.4544616,
"hits" : [
{
"_index" : "students",
"_id" : "1",
"_score" : 1.4544616,
"_source" : {
"name" : "Mary Major",
"classes" : [
"CS101",
"CS102",
"MATH101"
],
"min_required" : 2
}
},
{
"_index" : "students",
"_id" : "2",
"_score" : 0.5013843,
"_source" : {
"name" : "John Doe",
"classes" : [
"CS101",
"MATH101",
"ENG101"
],
"min_required" : 2
}
}
]
}
}
要使用脚本指定文档应匹配的最小术语数量,请在 minimum_should_match_script
字段中提供该脚本。
GET students/_search
{
"query": {
"terms_set": {
"classes": {
"terms": [ "CS101", "CS102", "MATH101" ],
"minimum_should_match_script": {
"source": "Math.min(params.num_terms, doc['min_required'].value)"
}
}
}
}
}
参数
查询接受字段名称 (<field>
) 作为顶级参数
GET _search
{
"query": {
"terms_set": {
"<field>": {
"terms": [ "term1", "term2" ],
...
}
}
}
}
<field>
接受以下参数。除 terms
外,所有参数都是可选的。
参数 | 数据类型 | 描述 |
---|---|---|
terms | 字符串数组 | 要在 <field> 中指定的字段中搜索的术语数组。只有当所需数量的术语与文档的字段值完全匹配(包括正确的间距和大小写)时,文档才会在结果中返回。 |
minimum_should_match_field | 字符串 | 指定返回文档所需匹配术语数量的数值字段的名称。您必须指定 minimum_should_match_field 或 minimum_should_match_script ,但不能同时指定两者。 |
minimum_should_match_script | 字符串 | 一个脚本,返回在结果中返回文档所需匹配术语的数量。您必须指定 minimum_should_match_field 或 minimum_should_match_script ,但不能同时指定两者。 |
提升 | 浮点数 | 一个浮点值,指定此字段对相关性得分的权重。高于 1.0 的值会增加字段的相关性。介于 0.0 和 1.0 之间的值会降低字段的相关性。默认值为 1.0。 |