gpt4 book ai didi

node.js - ElasticSearch:如何使用 ElasticSearch API 仅返回特定字段?

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:27 26 4
gpt4 key购买 nike

我正在使用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 的 Node 客户端实现相同的目的 -

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

最佳答案

_source 也可以用作查询的一部分。在主体 block 中添加 _source 作为 query 的同级。更新如下:

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

关于node.js - ElasticSearch:如何使用 ElasticSearch API 仅返回特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com