【问题标题】:How to merge the results of two queries to different indices in Elasticsearch?如何将两个查询的结果合并到 Elasticsearch 中的不同索引?
【发布时间】:2015-08-28 18:17:36
【问题描述】:

我正在索引main-kittens 中搜索Kitty 类型的文档。现在,我想进行一个实验。对于某些用户,我想改为搜索experiment-kittens。类型相同——Kitty,所有字段的值都与主索引中的值相同,但字段Bio 在主索引中始终为空,但在实验中它存储了巨大的字符串。

现在,问题是由于内存/磁盘限制,我无法为所有小猫存储 Bio。所以experiment-kittens 只有最近的小猫(比如上个月)。

我希望对大多数用户保持完整的搜索(即始终使用主索引)。对于挑选出来的,我想合并结果。逻辑应该是:

search userquery + date_created < 1 month ago in experiment-kittens
search userquery + date_created > 1 month ago in main-kittens

结果应该按create_date排序,在我的应用中排序太多了。

有没有办法让 elastic 对两个索引执行两个不同的查询并合并结果?

(我也确信这个问题可能有更优化的解决方案,如果你有的话请告诉我)。

【问题讨论】:

  • 您尝试过哪些解决方案?

标签: c# elasticsearch nest


【解决方案1】:

您可以使用一个 Elasticsearch 请求搜索多个索引,方法是使用逗号分隔索引名称。然后您可以使用missing filter 来区分这两个索引(一个具有Bio 字段而另一个没有)。然后您可以使用range filter 根据date_created 字段的值进行过滤。最后,您可以使用sort API 根据date_created 字段的值进行排序。

将所有这些放在一起,您需要的 Elasticsearch 查询如下:

POST main-kittens,experiment-kittens/Kitty/_search
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "bool": {
               "should": [
                  {
                     "bool": {
                        "must": [
                           {
                              "missing": {
                                 "field": "Bio"
                              }
                           },
                           {
                              "range": {
                                 "date_created": {
                                    "to": "now-1M"
                                 }
                              }
                           }
                        ]
                     }
                  },
                  {
                     "bool": {
                        "must_not": [
                           {
                              "missing": {
                                 "field": "Bio"
                              }
                           }
                        ],
                        "must": [
                           {
                              "range": {
                                 "date_created": {
                                    "from": "now-1M"
                                 }
                              }
                           }
                        ]
                     }
                  }
               ]
            }
         }
      }
   },
   "sort": [
      {
         "date_created": {
            "order": "desc"
         }
      }
   ]
}

您可以将"match_all": {} 替换为您可能拥有的任何自定义查询。

【讨论】:

  • missing filter 是缺失的部分(双关语)。也感谢您提供完整的查询。
猜你喜欢
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 2022-01-06
  • 2021-10-09
  • 1970-01-01
  • 2015-09-08
  • 2021-09-25
  • 2013-07-25
相关资源
最近更新 更多