How Meilisearch selects the primary key
When you add documents to a new index, Meilisearch tries to detect the primary key automatically. It looks for an attribute ending inid (case-insensitive). If it finds exactly one, it uses that attribute. If it finds multiple candidates or none, it returns an error.
You can also set the primary key explicitly when creating the index or when adding documents:
primaryKey query parameter when adding documents:
Accepted types
Primary key values must be either integers or strings. Strings can contain alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_).
| Type | Example | Valid |
|---|---|---|
| Integer | 42 | Yes |
| String | "product-123" | Yes |
| String with UUID | "550e8400-e29b-41d4-a716-446655440000" | Yes |
| Float | 3.14 | No |
| Boolean | true | No |
| Null | null | No |
Choose a good primary key
Use your source system’s ID
If your documents come from a database, use the existing unique identifier. This makes it easy to keep Meilisearch in sync:PUT (add or update) using the same ID, and Meilisearch merges the changes into the existing document.
UUIDs vs sequential integers
Both work well. Choose based on your use case:| Approach | Pros | Cons |
|---|---|---|
Sequential integers (1, 2, 3) | Simple, compact, easy to debug | Requires a central ID generator, reveals document count |
UUIDs (550e8400-...) | No coordination needed, safe for distributed systems | Longer, harder to read in logs |
Composite strings (category-123) | Human-readable, encodes context | Must guarantee uniqueness across categories |
Anti-patterns to avoid
Using a non-unique field
If two documents share the same primary key value, the second one overwrites the first. This is by design (it enables updates), but accidental duplicates cause data loss:Using a field that changes
If you use a field that can change over time (like a URL or slug), updating the document becomes difficult. When the “ID” changes, Meilisearch treats it as a new document instead of an update.Relying on auto-detection with multiple ID fields
If your documents have fields likeid, product_id, and user_id, Meilisearch cannot auto-detect which one to use and returns an error. Always set the primary key explicitly when your documents have multiple fields ending in id.
Change the primary key
The primary key cannot be modified once set. If you need to change it:- Export your data from the current index
- Delete the index
- Create a new index with the correct primary key
- Re-import your data
Next steps
Add and update documents
Learn how document operations use the primary key
Primary key reference
Technical details about primary key handling