Multiple OR Phrases Text Search in Atlas / Realm

Greetings. I’m looking to text search for multiple phrases (name variations) using OR conditions. I’m using a Realm function in Atlas; the collection has and index of the two fields I want to search. This forum post appears to offer a solution, but I can’t get @Doug_Tarr code to work in my function. Below is my current function; what I’d like is for the search term “Pink Panther” to be an array of OR variations ([“Pink Panther”, “Pinkerton J. Panther”, “Pinky Pants”, etc.]). Thanks!

exports = async function(request){ return await db.collection .find({ $text: { $search: "Pink Panther" } }) .sort( { "Published": -1, "_id": 1 } ) .limit(10) .toArray(); }

Can you share your index definition?

It looks like in your sample code you’re using $text indexes (linked here), but in order to take advantage of Doug’s linked example, you would need to use Atlas Search and create an index on the fields you want to search on. (Then use compound to search the multiple fields)

Also this blog outlines the differences between $text and Atlas Search. Sounds like Atlas Search is better suited.

2 Likes

Thanks Elle. I’m still learning MongoDB, but I mostly get what you’re saying. Does the screenshot below from Compass help explain the index I have in my collection? I’ll see if I can wrap my head around the compound examples. (I couldn’t get any of this forum thread’s code to work either.) Also, should the path variable contain the individual fields I want to search, or the name of the text index (which contains those same fields, “article+snippet” in my collection)?

Hi Jet_Hin!

I can totally relate to this issue, I experienced the same! I recommend creating an Atlas Search index using the JSON editor in the Atlas UI instead of utilizing Compass (it’s much easier). This can be done by

  1. Clicking the Create Search Index button after creating your cluster

  2. Then choosing your editor

  3. Here is an example of how an index can look like

This tutorial helped me a lot when it came to understanding how to create an index and gives an in depth walk through. After successfully creating the Search index, try following through the documents Elle shared and then trying Doug’s code.

4 Likes

Thanks @Elle_Shwer and @Humayara_Karim. I was able to create an index (still not sure exactly what the indexing in Compass does) and I believe this simple aggregation pipeline (a confusing term IMO for search parameters) did the trick. Here it is for posterity:

.aggregate([{
	$search: {
		phrase: {
			query: ["phrase one", "phrase two"],
			path: ["title", "description"]
		}
	}
}])
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.