Coerce

The coerce mapping parameter controls how values are converted to the expected field data type during indexing. This parameter lets you verify that your data is formatted and indexed properly, following the expected field types. This improves the accuracy of your search results.


Examples

The following examples demonstrate how to use the coerce mapping parameter.

Indexing a document with coerce enabled

  1. PUT products
  2. {
  3. "mappings": {
  4. "properties": {
  5. "price": {
  6. "type": "integer",
  7. "coerce": true
  8. }
  9. }
  10. }
  11. }
  12. PUT products/_doc/1
  13. {
  14. "name": "Product A",
  15. "price": "19.99"
  16. }

copy

In this example, the price field is defined as an integer type with coerce set to true. When indexing the document, the string value 19.99 is coerced to the integer 19.

Indexing a document with coerce disabled

  1. PUT orders
  2. {
  3. "mappings": {
  4. "properties": {
  5. "quantity": {
  6. "type": "integer",
  7. "coerce": false
  8. }
  9. }
  10. }
  11. }
  12. PUT orders/_doc/1
  13. {
  14. "item": "Widget",
  15. "quantity": "10"
  16. }

copy

In this example, the quantity field is defined as an integer type with coerce set to false. When indexing the document, the string value 10 is not coerced, and the document is rejected because of the type mismatch.

Setting the index-level coercion setting

  1. PUT inventory
  2. {
  3. "settings": {
  4. "index.mapping.coerce": false
  5. },
  6. "mappings": {
  7. "properties": {
  8. "stock_count": {
  9. "type": "integer",
  10. "coerce": true
  11. },
  12. "sku": {
  13. "type": "keyword"
  14. }
  15. }
  16. }
  17. }
  18. PUT inventory/_doc/1
  19. {
  20. "sku": "ABC123",
  21. "stock_count": "50"
  22. }

copy

In this example, the index-level index.mapping.coerce setting is set to false, which disables coercion for the index. However, the stock_count field overrides this setting and enables coercion for this specific field.