Skip to main content

Key Generation

Key Strategies

StrategyUsage on this datasource
AssignedA mapped key becomes _id; an omitted ID may be generated automatically.
Auto-incrementNo numeric auto-increment key; native document IDs use the generation and return path described below.
UUIDUse UUID32 or UUID36 with a string key field.
SequenceNo sequence-key strategy on this datasource.
CustomGenerate business IDs before insertion; callbacks cannot read numeric auto-increment keys.

Use a Generated ID

POST without a document ID lets Elasticsearch generate _id. It is separate from any business id or uid field in _source.

Provide a writable String id property on UserInfo. The following Mapper definitions fill it after insertion:

@Insert(value = "POST /user_info/_doc {\"name\": #{name}}",
useGeneratedKeys = true, keyProperty = "id")
int insert(UserInfo item);

After mapper.insert(item), read item.getId(). These examples pass one entity argument, not an argument wrapped in @Param.

Note

The generated-key column is _ID. Use _ID when specifying keyColumn, and receive it in a String property. Elasticsearch does not generate numeric identity keys.

Use an Assigned ID

To use an application ID, put it in the request path:

jdbc.executeUpdate(
"PUT /user_info/_doc/{?}?refresh=wait_for {\"name\": ?}",
new Object[] { "1001", "mali" });

Writing the same document ID replaces its content. Use _update for partial changes.

With the Builder API or BaseMapper, an assigned single mapped primary key also becomes the Elasticsearch _id. Unmarked business fields do not affect _id.

When no ID is supplied, Elasticsearch can generate _id instead of rejecting the write under a relational non-null primary-key constraint. If your application requires assigned IDs, validate the value before insertion.

Insert strategyWhen the primary key already exists
Into (default)Reports a duplicate-key error.
IgnoreSkips the document and returns 0; other errors still propagate.
UpdateUpdates only the supplied fields of an existing document, or inserts a new document.

Custom Key Generators

A beforeApply handler can generate a business ID, assign it to the entity, and include it in the insert request. An afterApply callback is also usable, but Elasticsearch does not provide numeric identity keys to read back from it.

For example, assign an order number in the application before insertion. To obtain an automatically generated string _id, use Generated IDs above. See Key Generators for custom-generator configuration.

Choosing the key source

For method annotations and Mapper files, use useGeneratedKeys with the default key source. The generated-key result is separate from the statement's ordinary result set; do not set generatedKeySource="resultSet" for these inserts.

The examples above show the supported generated-key path, including how to select the returned column with keyColumn.