Atlas Search - how to create OR query on multiple autocomplete fields

I have this search index:

I’m trying to create a search query that receives a string and returns all users of whom username OR fname OR lname includes that string.

This is what I have for username search:

$search: {
                index: 'User',
                autocomplete: {
                    query: values.query,
                    path: 'username',
                }
            }

How do I add OR fname OR lname?

What I’ve tried so far (none worked):

$search: {
    index: 'User',
    autocomplete: {
        query: values.query,
        path: ['username', 'fname', 'lname']
    }
}

$search: {
     index: 'User',
     filter {
          $or {
                autocomplete: {
                    query: values.query,
                    path: 'username'
                },
                autocomplete: {
                    query: values.query,
                    path: 'fname'
                },
                autocomplete: {
                    query: values.query,
                    path: 'lname'
                }
            }
        }
}

When you say “none worked”, do you mean you got not results or it didn’t work like an OR statement?

If the latter, try formatting your query using compound with should statements.

1 Like

I meant that these attempts resulted in an error.

To your suggestion - did you mean to run such query:

$search: {
      index: "User",
      compound: {
        should: [{
          autocomplete: {
            query: "marty",
            path: "username"
          }
        }],
        should: [{
          autocomplete: {
            query: "marty",
            path: "fname"
          }
        }],
        should: [{
          autocomplete: {
            query: "marty",
            path: "lname"
          }
        }]
      }
    }

It doesn’t give me all possible results (I use Search Tester which should retrieve up to 10 documents, yet it only retrieves 3 - satisfying one of each should).

Are you able to provide some sample documents and the expected output? This would make it easier to reproduce what you’re seeing on your side.

From your example, you can also try putting all the autocomplete’s into a single should operator, something like:


{
	'$search': {
     'index': 'User',
     'compound':{
        should: [
        	{
                autocomplete: {
                    query: 'marty',
                    path: 'username'
                }
            },
            {
                autocomplete: {
                    query: 'marty',
                    path: 'fname'
                }
            },
            {
                autocomplete: {
                    query: 'marty',
                    path: 'lname'
                }
            }
            ]
        }
	}
}

Regards,
Jason

1 Like

This one worked, thank you!

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