如何使用bool来限制Elasticsearch查询结果?

时间:2016-07-04 17:48:01

标签: ruby-on-rails ruby elasticsearch

在我的Rails应用程序中,我有2个模型:User(id)&文档(id,user_id,document_title,document)

  def self.search(query)
    __elasticsearch__.search(
      {
        query: {
          multi_match: {
            query: query,
            fields: ['document_title^10', 'document']
          }
        },
      }
  end

我正在使用上面的搜索查询,该查询非常适合整个表格的返回结果。问题是,结果不仅限于current_user。我正在尝试更新搜索方法,只返回current_user的结果。根据文档,我正在做:

  def self.search(query, user_id)
    __elasticsearch__.search(
      {
        bool: {
          filter: ["user_id", user_id]
        },
        query: {
          multi_match: {
            query: query,
            fields: ['document_title^10', 'document']
          }
        },
      }
  end

然而,这是错误的:

[400] {"error":{"root_cause":[{"type":"search_parse_exception","reason":"failed to parse search source. unknown search element [bool]","line":1,"col":2}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"documents","node":"52GAD0HbT4OlekjesTZY_A","reason":{"type":"search_parse_exception","reason":"failed to parse search source. unknown search element [bool]","line":1,"col":2}}]},"status":400}

1 个答案:

答案 0 :(得分:2)

我不确定您正在查看哪些文档,但该查询不正确:多匹配查询应该在bool查询的must子句中。

{
   query: {
     bool: {
       must: [{
        multi_match: {...}
      }],
      filter: [{
        term: {user_id: user_id}
      }]
    }
  }
}