Document Identifier
Every document has an identifier field _id. The identifier field serves as the primary key for the document and can be either auto-generated or custom-assigned.
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. |
|---|---|
Customizable Identifier: | If preferred, you can customize the _id as a string or JSON‑object. (See Custom Document Identifier) |
Retrieval by _id | You can fetch a document by its identifier. For more information, see Fetching a Document by _id. |
Auto-Generated Document Identifier
When inserting a document, unless manually supplied, Ditto automatically generates and assigns the new document a 128‑bit Universally Unique Identifier (UUID) to the _id field.
Custom Document Identifier
Following are a few key principles for handling IDs in Ditto:
- Do not include personally identifiable information (PII) in IDs
- IDs should be immutable; that is, unchangeable once assigned and permanent
- If an ID is formed by multiple fields, referred to as a composite key, those fields are not individually indexed and therefore searchable
Supplying a Custom String Identifier
The following snippet demonstrates creating a new document assigned the string value 123.
Forming a Composite Key Identifier
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, set the _id to a JSON-object when inserting a new document.
The following snippet demonstrates combining the vin and make fields to form a composite key:
Map<String, String> newCarId = new HashMap<>();
newCarId.put("vin", "123");
newCarId.put("make", "Toyota");
Map<String, Object> newCar = new HashMap<>();
newCar.put("_id", newCarId);
newCar.put("color", "blue");
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
"INSERT INTO cars DOCUMENTS (:newCar)",
Collections.singletonMap("newCar", newCar),
new Continuation<>() {
@NonNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NonNull Object o) {
if (o instanceof Result.Failure) {
// Handle failure
}
}
}
);
// "{vin: "123", make: "Toyota"}"
System.out.println(result.mutatedDocumentIDs()[0]);Fetching a Document by _id
Retrieve a document by its identifier (_id):
SELECT *
FROM cars
WHERE _id = '123'If querying a composite key identifier, use dot (.) notation:
SELECT *
FROM cars
WHERE _id.model = 'Toyota'For more information, see Ditto Query Language > IDs, Paths, Strings, and Keywords > Path Expressions