MongoDB full text search, autocomplete on two fields
Asked Answered
E

1

1

I am trying to implement MongoDB atlas search, and the objective is autocomplete on 2 fields.

I currently have this implementation:

const searchStep = {
    $search: {
        // Read more about compound here:
        // https://docs.atlas.mongodb.com/reference/atlas-search/compound/
        compound: {
            must: [
                {
                    autocomplete: {
                        query,
                        path: 'name',
                    },
                },
                {
                    autocomplete: {
                        query,
                        path: 'description',
                    },
                },
            ],
        },
    },
}

This does not seem to work, seems to only work when there is both a match on the name AND description. How can I fix this, so I query for both name and description?

I now tried using the wildcard option:

{
    wildcard: {
        query,
        path: ['name', 'description'],
        allowAnalyzedField: true,
    }
}

But the wildcard solution does not seem to work - no relevant results are returned...

Ecotype answered 31/7, 2020 at 5:33 Comment(0)
L
8

If you are trying to match on name or subscription, use should: instead of must:

must will require that all of the subqueries match, where as should requires that only 1 of them does.

const searchStep = {
    $search: {
        // Read more about compound here:
        // https://docs.atlas.mongodb.com/reference/atlas-search/compound/
        compound: {
            should: [
                {
                    autocomplete: {
                        query,
                        path: 'name',
                    },
                },
                {
                    autocomplete: {
                        query,
                        path: 'description',
                    },
                },
            ],
        },
    },
}
Laciniate answered 1/8, 2020 at 22:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.