首页 > 解决方案 > Elasticsearch - 从没有 id 的“_doc”请求中获取数据

问题描述

我正在使用 Elasticsearch 开发一个示例应用程序。我对它还很陌生,在我作为程序员的大部分时间里一直在使用 SQL 数据库,我发现 Elasticsearch 是在一个不同的世界。

从我的应用程序中,我的目标是根据使用它的用户检索一些文章。

我的问题是,例如,在使用_doc请求时,在这种情况下localhost:9200/publications/_doc/1,我有什么办法可以用 id 以外的东西获取数据1

例如,如果我有一个包含作者嵌套字段的文章映射(基本上是一个列表"name": "keyword",我可以基于作者 U 在作者列表中的事实以某种方式获取文章 X 吗?

我花了几乎一整天的时间在 Elasticsearch 官方文档上寻找答案,但我找不到任何东西可以回答这个问题。

任何帮助将不胜感激。

标签: elasticsearch

解决方案


这里需要的是查询。以下是获取请求而不是查询。

curl -H 'Content-Type: application/json' -XGET 127.0.0.1:9200/shakespeare/_doc/0?pretty

通过这个我们得到记录。这里的莎士比亚是索引。注意 Http 动词是 GET。

curl -H 'Content-Type: application/json' -XPOST 127.0.0.1:9200/shakespeare/_search?pretty -d '{
  "query": {
    "match": {
      "_id": "0"
    }
  }
}'

现在我们有一个查询。注意 Http 动词是 POST。在这里,我得到了 id 为 0 的文档。

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "shakespeare",
        "_type" : "_doc",
        "_id" : "0",
        "_score" : 1.0,
        "_source" : {
          "type" : "act",
          "line_id" : 1,
          "play_name" : "Henry IV",
          "speech_number" : "",
          "line_number" : "",
          "speaker" : "",
          "text_entry" : "ACT I"
        }
      }
    ]
  }
}

当有查询时,我们可以查询特定的记录和特定的字段,如下所示。在下面的查询中,我们查询了一条 id 为 0 的特定记录,并指定我只需要字段类型、line_id 等。

curl -H 'Content-Type: application/json' -XPOST 127.0.0.1:9200/shakespeare/_search?pretty -d '{
  "query": {
    "match": {
      "_id": "0"
    }
  },
  "fields": ["type", "line_id", "text_entry", "play_name"]
}'

请注意,下面的响应中包含 _source。

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "shakespeare",
        "_type" : "_doc",
        "_id" : "0",
        "_score" : 1.0,
        "_source" : {
          "type" : "act",
          "line_id" : 1,
          "play_name" : "Henry IV",
          "speech_number" : "",
          "line_number" : "",
          "speaker" : "",
          "text_entry" : "ACT I"
        },
        "fields" : {
          "play_name" : [
            "Henry IV"
          ],
          "text_entry" : [
            "ACT I"
          ],
          "type" : [
            "act"
          ],
          "line_id" : [
            1
          ]
        }
      }
    ]
  }
}

最后,如果我想省略_source,那么查询将如下所示,“_source”=false。

curl -H 'Content-Type: application/json' -XPOST 127.0.0.1:9200/shakespeare/_search?pretty -d '{
  "query": {
    "match": {
      "_id": "0"
    }
  },
  "fields": ["type", "line_id", "text_entry", "play_name"],
  "_source": false
}'

推荐阅读