Best way to implement fulltext search on a collection?

default discord avatar
Raigato
3 months ago
3 1

Hello 👋

I would like to create a fulltext search endpoint for one of my collections.

My idea for now it to follow this doc to create a standard text search with weights.
However, I have no idea where would be the best place to add the createdIndex line.

Also, I am wondering if I could just expose the payload admin search engine with some filters. Or if any other "idiomatic" way of doing this exist.

Thank you in advance for your guidance 🙏

  • default discord avatar
    pooledge
    2 months ago

    Just came back to it. So far it works for me with a named index created on server (re)start:

    const start = async () => {
    	// ...somewhere after payload itself has been initialized
    
    	payload.db.collections['items'].schema.index(
    		{ title: 'text', description: 'text' },
    		{
    			name: 'fulltext_1',
    			...
    		}
    	)
    }
  • default discord avatar
    pooledge
    3 months ago

    I am not sure whether this is the best way, but, after creating an index I've simply added an endpoint within server.ts to perform a text search, and it seems working:

    app.get('/search', async (req, res) => {
    	const query = `${req.query.q}` || '';
    
    	const results = await payload.db.collections['items'].find({
    		$text: { $search: query },
    	});
    
    	res.json({ results });
    });

    https://payloadcms.com/docs/database/mongodb#access-to-mongoose-models

    2 replies
    default discord avatar
    Raigato
    2 months ago

    Thank you @pooledge, did you created the $text index manually or added it somewhere in your codebase?
    Doing it manually might be an issue for me as I work with PR staging environments creating a new db every time

    default discord avatar
    pooledge
    2 months ago

    Just came back to it. So far it works for me with a named index created on server (re)start:

    const start = async () => {
    	// ...somewhere after payload itself has been initialized
    
    	payload.db.collections['items'].schema.index(
    		{ title: 'text', description: 'text' },
    		{
    			name: 'fulltext_1',
    			...
    		}
    	)
    }
Open the post
Continue the discussion in GitHub
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.