我有这样的映射:
{
printings: {
type: "nested",
properties: {
prop1: {type: "number"}
}
},
prop2: {type: "number"}
}
然后我想构建一个像这样的无痛查询:
"script": {
"lang": "painless",
"inline": "doc['prop1'] > (3 * doc['printings.prop2'])"
}
然而,在Sense中测试此功能不起作用。如果我用一个简单的数字替换嵌套的prop2,那么它确实有效。有没有办法在单个脚本查询中访问根和嵌套道具?
答案 0 :(得分:1)
不幸的是,您无法从root访问嵌套上下文,并且无法从嵌套中访问根上下文,因为嵌套文档是单独的文档,即使它们存储在父级附近。但您可以使用copy_to
字段功能使用不同的映射来解决此问题。这是一个映射:
{
"mappings": {
"sample": {
"properties": {
"printings": {
"type": "nested",
"properties": {
"prop2": {
"type": "integer",
"copy_to": "child_prop2"
}
}
},
"prop1": {
"type": "integer"
},
"child_prop2": {
"type": "integer"
}
}
}
}
}
在这种情况下,嵌套文档中的值将复制到父级。您不必显式填充此新字段,这是批量索引的示例:
POST http://localhost:9200/_bulk HTTP/1.1
{"index":{"_index":"my_index","_type":"sample","_id":null}}
{"printings":[{"prop2":1},{"prop2":4}],"prop1":2}
{"index":{"_index":"my_index","_type":"sample","_id":null}}
{"printings":[{"prop2":0},{"prop2":1}],"prop1":2}
{"index":{"_index":"my_index","_type":"sample","_id":null}}
{"printings":[{"prop2":1},{"prop2":0}],"prop1":2}
之后您可以使用此查询
{
"query": {
"script": {
"script": {
"inline": "doc['prop1'].value > (3 * doc['child_prop2'].value)",
"lang": "painless"
}
}
}
}
第一份文件不符合。第二个将匹配第一个子文档。第三个将与第二个子文档匹配。