Elasticsearch全局搜索多个索引上的不同过滤器

Rak*_*yal 5 java search search-engine elasticsearch

我们在Elastic Search中拥有多个索引,并且希望在所有索引中搜索数据,但是我们想对不同的索引应用不同的过滤器。

例如:

  • 依赖的索引很少client_id,因此需要client_id过滤器
  • 我们is_deleted在少数索引中有标志,因此is_deleted需要过滤器

在Elastic Search中应该如何处理?

另外,我们正在使用突出显示功能,应该向用户提供建议。但我们想忽略突出显示结果中的某些字段。是否可以在全球范围内排除某些字段?

san*_*rom 4

这是可能的,使用嵌套在布尔查询中的过滤查询

此示例说明了基本设置(注意如何使用不同的过滤器):

 @results = elastic_client.search([:dogs, :cats], {
   :bool => {
     :should => [
       # cats
       {
         :filtered => {
           :query => {
             :multi_match => {
               :query => 'meow', # repeated, replace with a variable
               :type => 'phrase_prefix',
               :fields => ['name', 'age']
             }
           },
           :filter => {
             :and => [
               { :term => { :owner_id => '123' } },
               { :type => { :value => 'cat' } }
             ]
           }
         }
       },
       # dogs
       {
         :filtered => {
           :query => {
             :multi_match => {
               :query => 'meow', # repeated, replace with a variable
               :type => 'phrase_prefix',
               :fields => ['name', 'color']
             }
           },
           :filter => {
             :and => [
               { :term => { :kennel_id => '456' } },
               { :type => { :value => 'dog' } }
             ]
           }
         }
       }
     ]
   }
 })
Run Code Online (Sandbox Code Playgroud)

这个特定的代码可能适用于您的 ES 客户端,也可能不适用于您的 ES 客户端,但它应该给出一个相当好的概念。

请注意,查询“meow”出现两次,您可能需要使用变量来代替,以在两个索引中搜索相同的内容。另外,multi_match显然也可能是其他类型的查询。