[英]Elastic Search Terms Query
我在彈性搜索中的嵌套字段的術語查詢中有一個要求,其中嵌套字段值應與術語查詢中提供的值的數量完全匹配。 例如,考慮下面的查詢,其中我們對名為 Types 的嵌套字段進行了術語查詢。
獲取資產/_search
{
"size": "10",
"from": 0,
"query": {
"bool": {
"must": [
{
"nested": {
"path": "Types",
"query": {
"bool": {
"must": [
{
"term": {
"Types.Label.keyword":
["VOD, AOP"]
}
}
]
}
}
}
}
]
}
}
}
索引映射
{
"media-assets": {
"mappings": {
"dynamic": "true",
"properties": {
"Types": {
"type": "nested",
"properties": {
"Label": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "lowercase_normalizer"
},
"ngram": {
"type": "text",
"analyzer": "ngram_tokenizer_analyzer"
}
}
}
}
}
}
}
}
}
樣本文件:
{
"_source": {
"AssetId": 1657352,
"MaterialId": "XBV01001",
"AirDate": "1997-03-10T00:00:00Z",
"Types": [
{
"Type": "AOP"
},
{
"Type": "VOD"
}
]
}
}
上面的查詢應該返回字段類型正好有 2 個值的文檔,即“VOD”和“AOP”。如果一個文檔在字段類型中具有這兩個值以及其他一些值,那么它不應該返回該文檔,因為數字查詢中提供的術語的數量應與類型字段中存在的值的數量相匹配。
您需要使用下面搜索查詢中定義的script_score
以及 function 分數查詢。
添加帶有索引數據、映射、搜索查詢和搜索結果的工作示例
索引映射:
{
"mappings": {
"properties": {
"Types": {
"type": "nested"
}
}
}
}
指數數據:
{
"Types": [
{
"Label": "VOD"
},
{
"Label": "AOP"
},
{
"Label": "ABC"
}
]
}
{
"Types": [
{
"Label": "VOD"
},
{
"Label": "AOP"
}
]
}
搜索查詢:
{
"query": {
"function_score": {
"query": {
"bool": {
"must": [
{
"nested": {
"path": "Types",
"query": {
"bool": {
"must": [
{
"terms": {
"Types.Label.keyword": [
"VOD",
"AOP"
]
}
}
]
}
}
}
}
]
}
},
"functions": [
{
"script_score": {
"script": {
"source": "params._source.containsKey('Types') && params._source['Types'] != null && params._source.Types.size() == 2 ? 1 : 0"
}
}
}
],
"min_score": 1
}
}
}
搜索結果:
"hits": [
{
"_index": "67639937",
"_type": "_doc",
"_id": "1",
"_score": 1.0,
"_source": {
"Types": [
{
"Label": "VOD"
},
{
"Label": "AOP"
}
]
}
}
]
試試下面的。
{
"size": "10",
"from": 0,
"query": {
"bool": {
"must": [
{
"nested": {
"path": "Types",
"query": {
"bool": {
"must": [
{
"term": {
"Types.Label.keyword":
["VOD, AOP"]
}
},
{
"script": {
"script": {
"inline": "doc['Types.Label'].length == 2,
"lang": "painless"
}
}
}
]
}
}
}
}
]
}
}
}
注意:腳本查詢會降低性能,如果可能,請考慮在獲得結果后過濾查詢結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.