AnApprentice AnApprentice - 5 months ago 114
Ruby Question

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}


Help appreciated. Thanks

Answer

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