0

If my search query is "Caramel Cake", then the search results are ["Caramel Cake", "Red Velvet Cake", "Chocolate Truffle Cake", and many more] using my existing code.

I want the search result to be ["Caramel Cake"]

Existing Code:

const products = await Product.aggregate([
      {
        $search : {
          index: "default",
          compound: {
            should:[
              {
                autocomplete:{
                  query: query,
                  path: "prodname",
                  fuzzy: {maxEdits: 2, prefixLength: 2}
                }
              },
              {
                autocomplete:{
                  query: query,
                  path: "prodcategory",
                  fuzzy: {maxEdits: 2, prefixLength: 2}
                }
                
              }
            ],
            minimumShouldMatch: 1,
          }
        },
      },
      {
        $project: {
          prodname: 1,
          prodimages:1,
          score: {$meta: "searchScore"},
        },
      },
      {
        $sort: {  
          score: -1,
        },
      },
      { $limit: 10},
    ]);
MRane
  • 9
  • 2
  • Does this answer your question? [MongoDB: Text search (exact match) using variable](https://stackoverflow.com/questions/43779319/mongodb-text-search-exact-match-using-variable) – SuleymanSah Jun 04 '23 at 17:26
  • No! That solution is not for fuzzy full-text search. – MRane Jun 04 '23 at 17:41

1 Answers1

0

Hey you can perform a text operator search with the help of keywordlowercaser analyzer

  1. Create an Analyzer as below for your index
  2. Make sure you have a multi-form mapping to your search field.
  3. Use the text operator in the $search aggs pipeline

Analyzer should use keyword tokenizer (lower tokenfilters are options for your case)

"analyzers": [{
  "name": "keywordlowercaser",
  "tokenFilters": [{
      "type": "lowercase"
    },
    {
      "type": "icuFolding"
    }
  ],
  "tokenizer": {
    "type": "keyword"
  }
}]

Update your mappings for prodname/prodcategory as follows

"prodname": {
  "multi": {
    "stringKeyword": {
      "analyzer": "keywordlowercaser",
      "type": "string"
    }
  },
  "type": "string"
}

Update you query filter as follows, use this in your should clause

text: {
  path: [{
    value: property,
    multi: 'stringKeyword'
  }],
  query: values,
  fuzzy: { maxEdits: 2 }
}

refer to this https://www.mongodb.com/docs/atlas/atlas-search/analyzers/tokenizers/#std-label-keyword-tokenizer-ref

You will be able to understand how the search works