Francis Kim
Francis Kim

Reputation: 4285

MongoDB - $text operator search for phrase OR word(s)

I'm doing a full text search that requires phrase(s) OR word(s).

As per the documentation:

If the $search string includes a phrase and individual terms, text search will only match the documents that include the phrase. More specifically, the search performs a logical AND of the phrase with the individual terms in the search string.

For example, passed a $search string:

"\"ssl certificate\" authority key"

The $text operator searches for the phrase "ssl certificate" and ("authority" or "key" or "ssl" or "certificate" ).

Is it possible to do this natively via MongoDB? Only other way I see now is to use Elastic search on top.

Update - the following search does not work and will cause a BadValue Too many text expressions error:

{
    $or: [{
        $text: {
            $search: "\"ssl certificate\""
        }
    }, {
        $text: {
            $search: "authority key"
        }
    }]
}

Upvotes: 2

Views: 660

Answers (1)

Philipp
Philipp

Reputation: 69713

The only way to do this natively is by performing multiple queries - one for each phrase and one for all stand-alone words together - and then merge the results on the application layer.

When relevance ranking is important for your use-case, have mongodb also give you the text score and make use of it when merging your results.

Upvotes: 3

Related Questions