elasticsearch集群中如何发起get请求获取某个索引的最新文档?

How to make a get request to retrieve the latest document of an index in the elasticsearch cluster?

我正在开发一个 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,

的图片

我的 node.js 代码如下所示,

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)?

有人可以帮我解决这个问题吗?如果您能提供帮助,我将不胜感激。

提前致谢!

如果您的索引中有一个 timestamp 字段,即每个文档都被索引后 updated/added。然后你可以简单地在时间戳字段上执行 sort 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: {}}
 }
});