fields

It is often useful to index the same field in different ways for different purposes. This is the purpose of multi-fields. For instance, a string field could be mapped as a text field for full-text search, and as a keyword field for sorting or aggregations:

  1. PUT my-index-000001
  2. {
  3. "mappings": {
  4. "properties": {
  5. "city": {
  6. "type": "text",
  7. "fields": {
  8. "raw": {
  9. "type": "keyword"
  10. }
  11. }
  12. }
  13. }
  14. }
  15. }
  16. PUT my-index-000001/_doc/1
  17. {
  18. "city": "New York"
  19. }
  20. PUT my-index-000001/_doc/2
  21. {
  22. "city": "York"
  23. }
  24. GET my-index-000001/_search
  25. {
  26. "query": {
  27. "match": {
  28. "city": "york"
  29. }
  30. },
  31. "sort": {
  32. "city.raw": "asc"
  33. },
  34. "aggs": {
  35. "Cities": {
  36. "terms": {
  37. "field": "city.raw"
  38. }
  39. }
  40. }
  41. }

The city.raw field is a keyword version of the city field.

The city field can be used for full text search.

The city.raw field can be used for sorting and aggregations

Multi-fields do not change the original _source field.

New multi-fields can be added to existing fields using the PUT mapping API.

Multi-fields with multiple analyzers

Another use case of multi-fields is to analyze the same field in different ways for better relevance. For instance we could index a field with the standard analyzer which breaks text up into words, and again with the english analyzer which stems words into their root form:

  1. PUT my-index-000001
  2. {
  3. "mappings": {
  4. "properties": {
  5. "text": {
  6. "type": "text",
  7. "fields": {
  8. "english": {
  9. "type": "text",
  10. "analyzer": "english"
  11. }
  12. }
  13. }
  14. }
  15. }
  16. }
  17. PUT my-index-000001/_doc/1
  18. { "text": "quick brown fox" }
  19. PUT my-index-000001/_doc/2
  20. { "text": "quick brown foxes" }
  21. GET my-index-000001/_search
  22. {
  23. "query": {
  24. "multi_match": {
  25. "query": "quick brown foxes",
  26. "fields": [
  27. "text",
  28. "text.english"
  29. ],
  30. "type": "most_fields"
  31. }
  32. }
  33. }

The text field uses the standard analyzer.

The text.english field uses the english analyzer.

Index two documents, one with fox and the other with foxes.

Query both the text and text.english fields and combine the scores.

The text field contains the term fox in the first document and foxes in the second document. The text.english field contains fox for both documents, because foxes is stemmed to fox.

The query string is also analyzed by the standard analyzer for the text field, and by the english analyzer for the text.english field. The stemmed field allows a query for foxes to also match the document containing just fox. This allows us to match as many documents as possible. By also querying the unstemmed text field, we improve the relevance score of the document which matches foxes exactly.