我在术语查询中要求弹性搜索中的嵌套字段,其中嵌套字段值应该与术语查询中提供的值数量完全匹配。例如,考虑下面的查询,其中对名为Types的嵌套字段进行了术语查询。
获取资产/搜索
{
"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"
}
]
}
}上面的查询应该返回字段类型正好有两个值的文档,即"VOD“和"AOP".If文档具有这两个值以及字段类型中的一些其他值,然后它不应该返回该文档,因为查询中提供的术语数量应该与类型字段中的值数目相匹配。
发布于 2021-05-21 16:59:14
您需要像下面的搜索查询中定义的那样使用script_score和函数评分查询。
使用索引数据、映射、搜索查询和搜索结果添加工作示例
索引映射:
{
"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"
}
]
}
}
]发布于 2021-05-22 05:55:52
试试看以下几点。
{
"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"
}
}
}
]
}
}
}
}
]
}
}
}注意:脚本化的查询提供了缓慢的性能,如果可能的话,请考虑在获得结果后过滤查询结果。
https://stackoverflow.com/questions/67639937
复制相似问题