我正在开发一个node.js应用程序来从弹性集群获取索引的最新值。我的logstash 服务器每秒将数据传输到elasticsearch。因此,elasticsearch 索引每秒都会更新。每秒都会有一个新文档添加到elasticsearch 索引中。
这是一个示例 JSON 文档
{
"_index": "weather",
"_type": "doc",
"_id": "eMIs_mQBol0Vk4cfUzG5",
"_version": 1,
"_score": null,
"_source": {
"weather": {
"main": "Clouds",
"icon": "04n",
"description": "broken clouds",
"id": 803
},
"@version": "1",
"clouds": {
"all": 75
},
"main": {
"humidity": 36,
"pressure": 1022,
"temp": 41,
"temp_max": 26,
"temp_min": 26
},
"wind": {
"deg": 360,
"speed": 3.6
},
"visibility": 16093,
"@timestamp": "2018-08-03T05:04:35.134Z",
"name": "Santa Clara"
},
"fields": {
"@timestamp": [
"2018-08-03T05:04:35.134Z"
]
},
"sort": [
1533272675134
]
}
这是 table 的图片,
let express = require('express');
let app = express();
let elasticsearch = require('elasticsearch');
app.get('/', function(req, res) {
res.send('Hello World!');
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
let client = new elasticsearch.Client({
host: ['http://localhost:9200']
});
client.ping({
requestTimeout: 30000,
}, function(error) {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('Everything is ok');
}
});
async function getResponse() {
const response = await client.get({
index: 'weather',
type: 'doc',
id: 'KsHW_GQBol0Vk4cfl2WY'
});
console.log(response);
}
getResponse();
我能够根据索引的 id 检索 JSON 文档。但是,我想检索最新的 JSON 文档。如何配置我的服务器以每秒从服务器读取最新文档?有没有办法检索最新的 JSON 文档(无需提前知道 id)?
有人可以帮我解决这个问题吗?如果您能提供帮助,我将不胜感激。
提前致谢!
最佳答案
如果您的索引中有一个时间戳字段,并且该字段在每个文档编制索引后都会更新/添加。然后,您只需使用 size=1 对时间戳字段执行排序即可。
以下查询将为您提供最新值:
{
"query": {
"match_all": {}
},
"size": 1,
"sort": [
{
"timestamp": {
"order": "desc"
}
}
]
}
不确定node.js的语法,但类似这样的东西可以工作:
client.search({
index: 'weather',
type: 'doc'
body: {
sort: [{ "timestamp": { "order": "desc" } }],
size: 1,
query: { match_all: {}}
}
});
根据您的映射,您@timestamp因此您应该使用:
client.search({
index: 'weather',
type: 'doc'
body: {
sort: [{ "@timestamp": { "order": "desc" } }],
size: 1,
query: { match_all: {}}
}
});
关于javascript - 如何发出get请求来检索elasticsearch集群中某个索引的最新文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51663413/