首页 > 解决方案 > ElasticSearch:如何使用 ElasticSearch API 仅返回特定字段?

问题描述

我正在使用 ElasticSearch 7.3,查询一些文档,
我想在查询响应中只返回每个文档的特定字段,
我发现_source可以用来实现这一点,
我可以使用这个查询从 Kibana 做到这一点 -

GET /test/_search?_source=id
{
  "query": {
    "match_all": {}
  }
}

向我返回正确的数据 -

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 6,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : 1.0,
        "_source" : {
          "id" : 3
        }
      },
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "id" : 2
        }
      },
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : { }
      },
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "4",
        "_score" : 1.0,
        "_source" : {
          "id" : 4
        }
      },
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "5",
        "_score" : 1.0,
        "_source" : {
          "id" : 5
        }
      },
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "6",
        "_score" : 1.0,
        "_source" : {
          "id" : 6
        }
      }
    ]
  }
}

但我无法使用 ElasticSearch 的节点客户端实现相同的目标 -

const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })

let searchTest = async () => {
  let indexToQuery = 'test';
  let esQuery = {
    index: indexToQuery,
    //q: '_source:id',
    body: {
        "query": {
          "match_all": {}
        }
    }
  };
  console.log('esQuery =>\n', esQuery);

  const result = await client.search(esQuery);
  console.log("search resp => \n", result.body.hits.hits);
};

searchTest();

有人可以帮我找到实现我的用例的正确方法吗?

参考资料 -
https://www.elastic.co/guide/en/elasticsearch/reference/7.3/docs-get.html#get-source-filtering
https://www.elastic.co/guide/en/elasticsearch/client /javascript-api/16.x/api-reference.html#api-search

标签: node.jselasticsearch

解决方案


_source也可以用作查询的一部分。添加_sourcequerybody 块中的兄弟姐妹。更新如下:

{
  "query": {
    "match_all": {}
  },
  "_source": ["id"]
}

推荐阅读