Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Best way to implement fulltext search on a collection?

default discord avatar
Raigatolast year
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 🙏

  • Selected Answer
    default discord avatar
    pooledgelast year

    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
    pooledgelast year

    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

    3 replies
    default discord avatar
    Raigatolast year

    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
    pooledgelast year

    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
    deep-12418 months ago

    payload.db.collections['items'].schema.index(
    { title: 'text', description: 'text' },
    )

    Below error is coming when trying to implement this:
    Property 'collections' does not exist on type 'DatabaseAdapter'

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.