在elasticsearch中的脚本查询中访问_id或_parent字段 [英] accessing _id or _parent fields in script query in elasticsearch
问题描述
使用脚本编写搜索查询时,我可以使用 doc ['myfield']访问字段
when writing a search query with a script, I can access fields using "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字段?
how do I go about accessing the _id or _parent fields?
ctx对象似乎在搜索查询中不可用(虽然可以在更新API请求中访问它,为什么?)。
The "ctx" object does not seem to be available in a search query (while it is accessible in an update API request, why?).
请记住,我使用的是python语言而不是mvel,但是它们都提出了相同的问题。
Mind you, I am using the python language instead of mvel, but both of them pose the same question.
推荐答案
默认情况下,文档ID和父ID均以uid格式编制索引: type#id
。 Elasticsearch提供了可以用于从uid字符串中提取类型和ID的几种方法。这是在MVEL中使用这些方法的示例:
By default, both document id and parent id are indexed in uid format: type#id
. Elasticsearch provides a few methods that can be used to extract type and id from uid string. Here is an example of using these methods in 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中的脚本查询中访问_id或_parent字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!