Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Text Search AND multiple search words

I have an index on an array "keys" that I am using to provide full text functionality to my applicaiton.

With the release of 2.4.3, I'd like to utilize the "text" index type. I insured a "text" index type on my array "keys" and it seems to work SUPER fast (faster than my old keywords full text method).

The problem is, my app assumes that fields are inclusive (AND). By default, the text search ORs my parameters.

Does anyone know of a way to run a text search inclusively?

For example:

db.supplies.runCommand("text", {search:"printer ink"}) 

should return results with both printer and ink, instead of all results with either printer or ink.

like image 511
kmehta Avatar asked Jun 03 '13 17:06

kmehta


People also ask

Is MongoDB good for text search?

MongoDB provides text indexes to support text search queries on string content. text indexes can include any field whose value is a string or an array of string elements. To perform text search queries, you must have a text index on your collection.

How do I do a full-text search in MongoDB?

Implement full-text search in MongoDB AtlasGo to any cluster and select the “Search” tab to do so. From there, you can click on “Create Search Index” to launch the process. Once the index is created, you can use the $search operator to perform full-text searches.

How does text search work in MongoDB?

MongoDB text search uses the Snowball stemming library to reduce words to an expected root form (or stem) based on common language rules. Algorithmic stemming provides a quick reduction, but languages have exceptions (such as irregular or contradicting verb conjugation patterns) that can affect accuracy.


2 Answers

Give a try to:

db.supplies.runCommand("text", {search:"\"printer\" \"ink\""}) 

Also, here's a quote from docs:

If the search string includes phrases, the search performs an AND with any other terms in the search string; e.g. search for "\"twinkle twinkle\" little star" searches for "twinkle twinkle" and ("little" or "star").

Hope that helps.

like image 197
alecxe Avatar answered Oct 24 '22 03:10

alecxe


You can wrap each word in double-quotes:

let keywords = ctx.params.query.split(/\s+/).map(kw => `"${kw}"`).join(' '); match.$text = { $search: keywords, $caseSensitive: false }; 

There is a downside if the user inputs a quoted string this will not work. You'd have to parse out quoted strings first.

like image 28
chovy Avatar answered Oct 24 '22 01:10

chovy