我需要比较同一文档中实际值无关紧要的2个字段。请考虑以下文档:
_source: {
id: 123,
primary_content_type_id: 12,
content: [
{
id: 4,
content_type_id: 1
assigned: true
},
{
id: 5,
content_type_id: 12,
assigned: false
}
]
}
我需要查找未分配主要内容的所有文档。我找不到将primary_content_type_id与嵌套的content.content_type_id进行比较的方法,以确保它们是相同的值。这是我尝试使用脚本。我不认为我理解脚本,但这可能是解决这个问题的一种方法:
{
"filter": {
"nested": {
"path": "content",
"filter": {
"bool": {
"must": [
{
"term": {
"content.assigned": false
}
},
{
"script": {
"script": "primary_content_type_id==content.content_type_id"
}
}
]
}
}
}
}
}
请注意,如果我删除过滤器的脚本部分并将其替换为content_type_id = 12
中的另一个术语过滤器,并在primary_content_id = 12
处添加另一个过滤器,则它可以正常工作。问题是我不知道(对我的用例也不重要)primary_content_type_id
或content.content_type_id
的值是什么。对于content_type_id
与primary_content_type_id
匹配的内容,分配的内容是错误的。
弹性搜索可以检查吗?
答案 0 :(得分:7)
如果是嵌套搜索,则为searching the nested objects without the parent。不幸的是,没有隐藏的联接可以应用nested
个对象。
至少目前,这意味着您不会在脚本中同时收到“父”和嵌套文档。您可以通过用这两个脚本替换脚本并测试结果来确认这一点:
# Parent Document does not exist
"script": {
"script": "doc['primary_content_type_id'].value == 12"
}
# Nested Document should exist
"script": {
"script": "doc['content.content_type_id'].value == 12"
}
通过
object
循环,而不是固有地让ES为你做nested
)。这意味着您必须将文档和nested
文档重新索引为单个文档才能使其生效。考虑到你尝试使用它的方式,这可能不会太差异,甚至可能表现更好(特别是考虑到缺少替代方案)。
# This assumes that your default scripting language is Groovy (default in 1.4)
# Note1: "find" will loop across all of the values, but it will
# appropriately short circuit if it finds any!
# Note2: It would be preferable to use doc throughout, but since we need the
# arrays (plural!) to be in the _same_ order, then we need to parse the
# _source. This inherently means that you must _store_ the _source, which
# is the default. Parsing the _source only happens on the first touch.
"script": {
"script": "_source.content.find { it.content_type_id == _source.primary_content_type_id && ! it.assigned } != null",
"_cache" : true
}
我缓存了结果,因为此处没有动态发生(例如,不将日期与now
进行比较),因此缓存非常安全,从而使未来的查找更多更快。默认情况下,大多数过滤器都会被缓存,但scripts are one of the few exceptions。
因为必须比较两个值以确保它找到了正确的内部对象,所以你正在复制一些的工作量,但这实际上是不可避免的。拥有term
过滤器最有可能优于仅在没有它的情况下执行此检查。