Elasticsearch and OpenSearch accept any string as a document _id. The format choice affects routing, query patterns, and operational tooling. UUID v7 as the document ID gives time-ordered IDs that sort lexicographically by creation time — useful for log pipelines, event streams, and any index where documents are appended in time order. This page covers the practical patterns using the uuid npm package and the uuid6 Python package, with reference to the OpenSearch documentation and Elasticsearch reference.
Indexing documents with UUID v7
Node.js (Elasticsearch client)
import { Client } from "@elastic/elasticsearch";
import { v7 as uuidv7 } from "uuid";
const client = new Client({ node: "http://localhost:9200" });
await client.index({
index: "orders",
id: uuidv7(), // UUID v7 as document ID
document: {
customerId: "018f4b2a-7c3d-4000-8e5f-1a2b3c4d5e6f",
total: 99.99,
status: "placed",
},
});
Python (OpenSearch client)
from opensearchpy import OpenSearch
import uuid6
client = OpenSearch(hosts=[{"host": "localhost", "port": 9200}])
client.index(
index="orders",
id=str(uuid6.uuid7()), # UUID v7 document ID
body={
"customer_id": "018f4b2a-7c3d-4000-8e5f-1a2b3c4d5e6f",
"total": 99.99,
"status": "placed",
}
)
Time-range queries using the _id field
UUID v7 IDs encode a millisecond timestamp in their first 12 hex characters. Generate boundary values to query by time range:
def uuid7_boundary(target_ms: int) -> str:
"""Generate the smallest UUID v7 value at or after target_ms."""
ts_hex = format(target_ms, "012x")
# Format: xxxxxxxx-xxxx-7000-8000-000000000000
return f"{ts_hex[:8]}-{ts_hex[8:12]}-7000-8000-000000000000"
# Find all orders in the last hour
now_ms = int(time.time() * 1000)
since_ms = now_ms - 3_600_000
response = client.search(
index="orders",
body={
"query": {
"range": {
"_id": {
"gte": uuid7_boundary(since_ms),
"lt": uuid7_boundary(now_ms),
}
}
}
}
)
This leverages UUID v7’s lexicographic time ordering — guaranteed by RFC 9562 §5.7 — without requiring a separate @timestamp indexed field.
Bulk indexing with UUID v7
For high-throughput bulk indexing (log pipelines, event streams), pre-generate UUID v7 IDs on the producer side:
import { v7 as uuidv7 } from "uuid";
const events = rawEvents.map(event => ({
id: uuidv7(),
...event,
}));
// Prepare bulk request body
const body = events.flatMap(doc => [
{ index: { _index: "events", _id: doc.id } },
doc,
]);
await client.bulk({ body });
UUID v7 IDs generated in rapid succession within the same millisecond differ in their random bits, ensuring uniqueness. The Elasticsearch bulk API documentation covers batching, error handling, and refresh strategies.
Index lifecycle management with UUID v7 timestamps
For data streams and ILM (Index Lifecycle Management), UUID v7 document IDs can serve as a proxy for document age. Extract timestamps for rollover decisions:
{
"script": {
"source": "long ts = Long.parseUnsignedLong(params._source['_id'].replace('-','').substring(0,12), 16); return ts < params.cutoff_ms;",
"params": { "cutoff_ms": 1727308800000 }
}
}
Standard practice is still to index a @timestamp field for ILM — UUID v7 extraction via Painless script is suitable for ad hoc queries but not for production rollover policies. The Elasticsearch ILM documentation covers rollover, warm, cold, and delete phases.
Shard routing with UUID v7
Elasticsearch routes documents to shards using hash(_id) % number_of_shards. UUID v7 hashes distribute as evenly as UUID v4 — both have sufficient entropy in the full 128-bit value. The time-prefix in UUID v7 does not cause shard hotspots because the hash function (MurmurHash3) scrambles the input.
For custom routing (e.g. co-locating documents for a tenant on the same shard), use the routing parameter explicitly rather than relying on the document ID. The OpenSearch index data documentation covers custom routing configuration.
Further reading
- UUID v7 in Distributed Systems — ordering across services
- UUID Security — timestamp disclosure in document IDs
- UUID Generation Strategies — server vs client assignment
External references
- Elasticsearch _id field documentation
- OpenSearch documentation
- uuid6 on PyPI
- uuid npm package
- RFC 9562 — UUID standard
Frequently asked questions
Should I use UUID v4 or UUID v7 as Elasticsearch document IDs?
UUID v7 is the better default for append-heavy indexes. Elasticsearch routes documents to shards by hashing the document ID — UUID v7 distributes as evenly as UUID v4 across shards. The additional benefit of UUID v7 is that document IDs encode creation time, enabling time-range document lookups without a separate @timestamp field in the routing key. UUID v4 is preferable for IDs that appear in external API responses where timestamp disclosure is a concern. The Elasticsearch _id field documentation covers ID type constraints.
How do I query documents by UUID v7 time range in OpenSearch?
Generate boundary UUID v7 values for your target time range and use a range query on the _id field: {"range": {"_id": {"gte": "019236a7-0000-7000-8000-000000000000", "lt": "019236a8-0000-7000-8000-000000000000"}}}. The OpenSearch range query documentation covers term-level range queries. This avoids an index on @timestamp for simple time-bounded scans, though a dedicated timestamp field is faster for complex range filters.
Does UUID v7 affect OpenSearch index performance vs UUID v4?
Elasticsearch and OpenSearch use Lucene internally, which stores the _id field in an inverted index. UUID v7's time-ordered nature gives a slight write locality advantage for append-only indexes — new documents cluster near the end of the internal term dictionary. For mixed workloads (updates + inserts), the difference is negligible. Significant performance differences arise in relational databases with B-tree indexes, not in document stores. See the Elasticsearch indexing performance guide.