简体   繁体   中英

How to use bool to limit Elasticsearch query results?

In my Rails app I have 2 models: User(id) & Document(id,user_id, document_title,document)

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

I'm using the above search query which works great for return results across the entire table. The problem is, the results are not limited to the current_user. I'm trying to update the search method to only return results for the current_user. Per the docs, I'm doing:

  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

However, that is erroring with:

[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}

I'm not sure what docs you are looking at but that query isn't right: the multi match query should be in the must clause of the bool query.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM