How to treat quotes in user's query as exact match

61 views Asked by At

I'm trying to understand how to properly construct $search stage to treat query inside the quotes as exact match.

Example user's query: "code testing" results

At the end, I want to get search results that must have exact code testing sub-string in the "title" doc field and optional results string in a different forms, e.g. results, result.

So far, I created a search index with two field mappings:

  • one with lucene.standard analyzer - for exact matches
  • another with lucene.english analyzer - to match the rest of the user's query
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": [
        {
          "type": "string",
          "analyzer": "lucene.english",
          "searchAnalyzer": "lucene.english",
          
          "multi": {
            "title_standard": {
              "type": "string"
              "analyzer": "lucene.standard",
              "searchAnalyzer": "lucene.standard",
            }
          },
        }
      ]
    }
  }
}

Then in runtime I parse user's query, extract string from quotes, and create such $search stage:

{
  "$search": {
    "compound": {
      "must": [
        {
          "phrase": {
            "query": "code testing",
            "path": {
              "value": "title", 
              "multi": "title_standard"
            }
          }
        }
      ],
      "should": [
        {
          "text": {
            "query": "results",
            "path": "title"
          }
        }
      ]
    }
  }
}

Does this solution look correct? Is there a way to avoid query parsing? Maybe there is a more suitable index/query configuration for this use case?

1

There are 1 answers

0
eleoras On

I'd recommend using the lucene.keyword analyzer to achieve exact matches.

MongoDB published a blog about different exact match strategies that you could also try. But the goal of keyword is store the term exactly as it appears in the database.