9

Let's say I want to store documents like the one below:

{
  "item_id": 1,
  "item_price": 500,
  "currency": "USD"
}

I want the currency field to be like ENUM, so I can predefine the set of values, like: "USD", "GBP", "EUR" and so on...

I also would like that each value will be related to an integer, like hash map, so the set of values will look like this:

{ "USD":1, "GBP":2, "EUR":3 }

how shell I map this field?

2 Answers 2

9

You need to declare your enum in your indexing code and your document should be denormalized like this:

{
  "item_id": 1,
  "item_price": 500,
  "currency": "USD",
  "currency_id": 1
}

As for the data types, I suggest to declare the currency field as keyword and the currency_id field as byte or short depending on the number of currencies you need to track.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, thanks. But can I define a set of currencies (strings) in advance, so if I'll enter wrong currency which is not in the set ("USF" for example) elasticsearch will recognize my mistake? and another thing, according to you example I can by mistake enter "USD" with id of 2.
ES has a typing system and allows you to define mapping types, but doesn't make the kind of checks you're describing. It is up to you to make sure your indexing code is sound and consistent. Unit-test it ;-)
OK, So what are the benefits for making this field keyword type instead of string type.
It will not be analyzed, so you can run aggregations on it. if that's intended to be an enum, it doesn't really make sense to be anything else than a keyword
0

I suggest using keyword data type, it's pretty efficient

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.