You can edit documents by executing a Rhai function on all the documents of your database or a subset of them that you can select by a Meilisearch filter.

<aside> ⚠️ Running scripts on all documents is discouraged. Where possible, we recommend pre-filtering using a Meilisearch filter.

</aside>

Examples

Upper Case and Add Sparkles around Movie Titles

By indexing the movies dataset you can then run the following Rhai function on all of them. This function will uppercase the titles of the movies with an id > 3000 and add sparkles around it. All of that by leveraging the Rhai templating syntax.

curl <http://localhost:7700/indexes/movies/documents/edit> \\
  -H 'content-type: application/json' \\
  -d '{
    "filter": "id > 3000",
    "function": "doc.title = `✨ ${doc.title.to_upper()} ✨`"
  }'

Titles will go from Ariel to ✨ ARIEL ✨ or Star Wars to ✨ STAR WARS ✨.

Delete documents

By setting the doc variable to () (also known as NULL or nil), Meilisearch will delete the associated document. The following example will delete every document with an even id.

if doc.id % 2 == 0 {
	doc = ()
}

User-defined Context

Sometimes, it's useful to maintain the same function but introduce parameters. You can do this using the context parameter. For example, in this scenario, we delete all documents with an ID greater than the context idmax and add sparkles to the titles of the remaining documents.

curl <http://localhost:7700/indexes/movies/documents/edit> \\
  -H 'content-type: application/json' \\
  -d '{
    "context": { "idmax": 50 },
    "function": "
	    if doc.id >= context.idmax {
		    doc = ()
		  } else {
			  doc.title = `✨ ${doc.title} ✨`
			}
		"
  }'

Decaying Ranking Strategy

Some users want to implement a decay ranking system, often referred to as the Reddit-style or HackerNews-style post ranking. By following the formula found in this comprehensive article, you can achieve the same with Meilisearch. Sorting by ranking_score:desc on the first page of your website will provide the desired ranking. However, remember that the score remains static. Therefore, depending on your needs, you should set up this function in a cron job to run every minute, hour, or day.

# posted_at and now are Unix Epoch timestamps in seconds
# and must, therefore, be converted to hours (/ 60 / 60).
curl <http://localhost:7700/indexes/movies/documents/edit> \\
  -H 'content-type: application/json' \\
  -d '{
    "context": { "now": 1715423249 },
    "function": "
      let age_hours = (context.now - doc.posted_at) / 60 / 60;
      doc.ranking_score = doc.upvotes ** 0.8 / (age_hours + 2) ** 1.8;
		"
  }'

Create Nested Objects

In Rhai, accessing the field of an object doesn’t create it. To create a nested object in a document, you must use the #{} object syntax to create the objects individually.

doc._vectors = #{
  "default": #{
    embeddings: [1, 2, 3, 4]
  }
}