How to run a verbatim search using MongoDB's Atlas Search

Viewed 57

I'm trying to use MongoDB's Atlas Search to create a simple search engine.

I created an index for a field source that contains a long text in each document. Now I want to find all documents that contain exactly a specific string like "hello my name is".

So for example, a document with

source: "this is a long text and here comes hello my name is and here goes more text"

should be returned. But a document with

source: "this is another long text hi my name is and here goes even more text"

shouldn't be returned as the phrase doesn't appear exactly in the string.

So basically, what Google does when you run a verbatim search.

When I'm using the following command with an index built using the Standard Analyzer, I'm getting a lot of fuzzy results, i.e. documents where the source field only contains partial matches.

db.data.aggregate([
{
    '$search': {
        'index': 'default',
        'text': {'query': 'hello my name is','path': 'source'}
    }},
    {
        '$limit': 10
     },
     {  
         '$project': 
                    { '_id': 0,'source': 1}
      }
 ])
1 Answers

You should use keyword analyzer for this field. It searches all search query string as a single term. If you need ability to use both, full match and similarity/partial match on same field, so you can setup muliple analyzers for one field. For example, Standrt analyzer for partial string match and Keyword analyzer for exact match

Check multiple analyzers index mapping example

  "description": {
    "analyzer": "lucene.simple",
    "multi": {
      "keywordAnalyzer": {
        "analyzer": "lucene.keyword",
        "type": "string"
      }
    },
    "searchAnalyzer": "lucene.simple",
    "type": "string"
  }

Or just

  "description": {
    "analyzer": "lucene.keyword",
    "type": "string"
  }
Related