"Relaxing" query

Is there a way to "relax" a query when there are no matches?

For example, if a user searches "red shirts" and the operator is "AND" and there are no results, the operator would change to "OR"

You can use a bool query with 2 should clauses.

The And one with a boost
The Or one without any boost

So you will get both but elements which match AND will be on top.

A full example here:

Thanks, But we have the TF-IDF disabled for custom relevancy scoring, so it's a different use case

Even with no score I think what I said is still valid. Did you try?

I think I get your idea and I haven't tried it because I think it won't help because it relies on boosting the AND matches and, sort of, downranking the OR matches

In such case, it will be equivalent to an OR query. So in my example, if there ARE "red shirts" I would also get results for products which don't match both terms.

Yes. But they will be less important.

Otherwise you can do something like this I think:

bool
  Should 
    Match (and)
    Bool
      Must not
         Match (and)
      Must 
         Match (or)

We don’t know there are no results until all matches are returned to the coordinating node so this is not something that can be figured out on individual data nodes in a distributed system.
I know of search consultancies who put this sort of relaxation logic in their app’s client code for elasticsearch. The “tight” query is preferable because, yes, a “sloppy OR tight” query should still rank best hits the same way but will make a mess of any aggregations used to filter by things like department

They would less important according to TF-IDF, but it's disabled..

So I think I will go with implementing it on the application side. Thanks

When TFIDF is disabled the score is 1 I think.

So you will have documents with a score of 3 (match on AND but boosted + match on OR) and documents with a score of 1 (match on OR).

I think. Did you test it?

It works fine when TF-IDF is enabled, however we have custom scoring so TF-IDF isn't considered at all. My function_score query replaces the score..

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.