【问题标题】:accessing _id or _parent fields in script query in elasticsearch在 elasticsearch 的脚本查询中访问 _id 或 _parent 字段
【发布时间】:2013-03-21 17:03:37
【问题描述】:

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

【问题讨论】:

  • 你能告诉我访问 doc["my_field"] 你写了什么代码我应该在 yml 文件中添加任何东西还是我应该在我的配置中创建一个不同的文件/脚本文件夹??请告诉我,我正在为此寻找很长时间??

标签: elasticsearch


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2022-07-01
    相关资源
    最近更新 更多