elasticsearch 使用两个不同的排序(相同类型)字段合并两个bool查询的结果

h79rfbju  于 2023-03-29  发布在  ElasticSearch
关注(0)|答案(2)|浏览(209)

我有两个不同的索引,它们以不同的结构存储数据。我想根据每个索引中相同类型但名称不同的字段来合并这些索引上的查询结果。例如:调用索引具有

{
  callTime:"2023-03-27T23:16:01Z",
  title:"hello world!",
  type:"ZOOM"
}

电子邮件索引具有:

{
  timestamp:"2023-03-26T22:06:00Z",
  subject:"Hello World again!",
  bcc:"abc@test.com"
}

现在这些索引可能有很多数据。我希望基于一些查询的最后25个对象,然后两个索引都按callTime/timestamp排序。它可以包含任何数量的对象,只要它们按callTime/timestamp字段排序并满足在其索引上写入的查询。
我试着用多重搜索,什么也没找到。

cvxl0en2

cvxl0en21#

您可以在查询中使用排序脚本,如下所示,它将满足您的要求。
我有索引2由你在单独的索引文件:

POST call/_doc
{
  "callTime":"2023-03-27T23:16:01Z",
  "title":"hello world!",
  "type":"ZOOM"
}

POST email/_doc
{
  "timestamp":"2023-03-26T22:06:00Z",
  "subject":"Hello World again!",
  "bcc":"abc@test.com"
}

下面是query,它将给予预期的结果,您可以使用条件更新查询或添加大小参数以获得特定数量的结果等:

POST call,email/_search
{
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": "if(doc.containsKey('callTime')){return doc['callTime'].value.toInstant().toEpochMilli()} else if(doc.containsKey('timestamp')){return doc['timestamp'].value.toInstant().toEpochMilli()}"
      },
      "order": "asc"
    }
  }
}

答复:

{
  "took": 575,
  "timed_out": false,
  "_shards": {
    "total": 2,
    "successful": 2,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 2,
      "relation": "eq"
    },
    "max_score": null,
    "hits": [
      {
        "_index": "email",
        "_id": "u_SqJocBYGx8nLsboyew",
        "_score": null,
        "_source": {
          "timestamp": "2023-03-26T22:06:00Z",
          "subject": "Hello World again!",
          "bcc": "abc@test.com"
        },
        "sort": [
          1679868360000
        ]
      },
      {
        "_index": "call",
        "_id": "uvSqJocBYGx8nLsbHyfp",
        "_score": null,
        "_source": {
          "callTime": "2023-03-27T23:16:01Z",
          "title": "hello world!",
          "type": "ZOOM"
        },
        "sort": [
          1679958961000
        ]
      }
    ]
  }
}
jchrr9hc

jchrr9hc2#

在一个索引的time字段中添加别名,例如在email索引中的timestamp字段中添加一个名为callTime的别名字段,然后使用callTime在索引中搜索
参见:
https://www.elastic.co/guide/en/elasticsearch/reference/current/field-alias.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multiple-indices.html

相关问题