node.js - 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
解决方案
_source
也可以用作查询的一部分。添加_source
为query
body 块中的兄弟姐妹。更新如下:
{
"query": {
"match_all": {}
},
"_source": ["id"]
}
推荐阅读
- python - 以某种方式/形式生成数字/文本
- python-3.x - 修复 WSL 上的 Python3 pip 安装
- python-3.x - Python VLC player.next() 控件
- date - 谷歌表格 | 周六至周三返回上周五的日期,周四和周五除外
- unit-testing - 通过命令行运行 pyspark 单元测试用例的命令
- facebook - 我可以在我的 Facebook 页面上将一些元数据绑定到来自客户聊天的 webhook 消息吗?
- javascript - 相当于react中的directory、mozdirectory和webkitdirectory?
- html - 当光标悬停在图片上方时如何使图片旋转
- c# - Avalonia 的 ReactiveUI 示例:UserControl 视图不起作用
- c++ - 如何返回 clang::DeclRefExpr 对象对应的父表达式