在elasticsearch中的脚本查询中访问_id或_parent字段

时间:2013-03-20 16:48:46

标签: elasticsearch

使用脚本编写搜索查询时,我可以使用" 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,但它们都提出了同样的问题。

1 个答案:

答案 0 :(得分:4)

默认情况下,文档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