使用脚本编写搜索查询时,我可以使用“doc ['myfield']”访问字段

curl -XPOST 'http://localhost:9200/index1/type1/_search' -d '
{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "script": {
          "script": "doc[\"myfield\"].value>0",
          "params": {},
          "lang":"python"
        }
      }
    }
  }
}'

如何访问_id或_parent字段?

“ctx”对象似乎在搜索查询中不可用(虽然可以在更新API请求中访问它,为什么?)。

请注意,我使用的是python语言而不是mvel,但是它们两个都提出了相同的问题。

最佳答案

默认情况下,文档ID和父ID均以uid格式建立索引:type#id。 Elasticsearch提供了一个few methods,可用于从uid字符串中提取类型和id。这是在MVEL中使用这些方法的示例:

curl -XDELETE localhost:9200/test
curl -XPUT localhost:9200/test -d '{
    "settings": {
        "index.number_of_shards": 1,
        "index.number_of_replicas": 0
    },
    "mappings": {
        "doc": {
            "properties": {
                "name": {
                    "type": "string"
                }
            }
        },
        "child_doc": {
            "_parent": {
                "type": "doc"
            },
            "properties": {
                "name": {
                    "type": "string"
                }
            }
        }
    }
}'
curl -XPUT "localhost:9200/test/doc/1" -d '{"name": "doc 1"}'
curl -XPUT "localhost:9200/test/child_doc/1-1?parent=1" -d '{"name": "child 1-1 of doc 1"}'
curl -XPOST "localhost:9200/test/_refresh"
echo
curl "localhost:9200/test/child_doc/_search?pretty=true" -d '{
    "script_fields": {
        "uid_in_script": {
            "script": "doc[\"_uid\"].value"
        },
        "id_in_script": {
            "script": "org.elasticsearch.index.mapper.Uid.idFromUid(doc[\"_uid\"].value)"
        },
        "parent_uid_in_script": {
            "script": "doc[\"_parent\"].value"
        },
        "parent_id_in_script": {
            "script": "org.elasticsearch.index.mapper.Uid.idFromUid(doc[\"_parent\"].value)"
        },
        "parent_type_in_script": {
            "script": "org.elasticsearch.index.mapper.Uid.typeFromUid(doc[\"_parent\"].value)"
        }
    }
}'
echo

关于elasticsearch - 在elasticsearch中的脚本查询中访问_id或_parent字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15529701/

10-15 14:42