Identifier: Default and Custom
The Ditto query engine supports various filter operations for optimal data retrieval.
As the basis of data organization and access in Ditto, the query engine indexes the document _id so you can quickly and precisely access your data.
Each document must be assigned a unique identifier. When invoking the upsert method to create a new document, unless manually supplied, Ditto automatically generates and assigns the new document a 128‑bit Universally Unique Identifier (UUID).
Following are the main features and qualities associated with the _id field:
- Document Identification: The document _id field serves as the primary key identifying the document in Ditto. For more information, see Primary key, as follows.
- Customizable Primary Key: If preferred, you can customize the primary key as a string or JSON blob object. For more information, see Custom Configuration.
- Retrieval by _id: Using the FindById method, you can fetch a document by its primary key. For more information, see Fetching a Document by _id.
The first set of fields within each document uniquely identifies the data that its document object encodes. When grouped in a collection, this _id serves as the primary key identifying the document in the collection.
In addition, you can improve organization, enhance querying capabilities, and establish specific relationships, using a combination of two or more fields to form a more specific and meaningful composite key. It is important to note there are distinct tradeoffs that you must closely consider before choosing to create a composite key.
For more information, see Custom Configurations , as follows.
If supplying your own document ID, you can encode your value in a stringor, if forming a composite key, a JSON blob object made up of two or more values of the string or number type.
You can configure a custom document ID only at the time of document creation.
Once a document is created, to ensure consistency and uniqueness throughout the platform, the unique identifier that either Ditto automatically generated and assigned or you manually assigned becomes permanent and cannot be changed at a later time.
The following snippet demonstrates creating a new document assigned the string value 123abc.
The decision to opt for a composite key depends on your specific use case. Following are typical use cases for forming a composite key:
- To implement additional logic to handle (or prevent) duplicate writes.
- To simplify queries and enhance efficiency in the querying process.
To form a composite key, when calling upsert() to create a new document, pass the fields you want to combine to form the new primary key in an embedded map structure.
The following snippet demonstrates combining the user_id and work_id fields to form the 123abc780 composite key:
Fetch a single document by its primary key: the document _idfield by invoking the Find By ID method.