Search code examples
scalaelasticsearchelastic4s

Multifield in Elastic4s 5.x


I'm currently using Elastic4s v5.0, which still has the multifield type used to index a field in more than one way.

elasticClient.execute(createIndex("foo") mappings (
  mapping("bar").as(
    multiField("baz").as(
      textField("baz") analyzer myAnalyzer,
      textField("original") index NotAnalyzed
    )
  )
)

However, I get the following error:

No handler for type [multi_field] declared on field []

The answer ElasticSearch 5: MapperParserException with multi_field and documentation here https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-fields.html says to use "fields" instead, but I cannot find how to do this in elastic4s.


Solution

  • In Elasticsearch any multifield has a primary field which is kind of like a parent field and then it has secondary fields. The primary field (primary and secondary is my terminology by the way), is accessed with a and the secondary fields are accessed as a.b, a.c and so on.

    This might not be how you would first imagine a multi field to be, because you might just think that there's a, b, c as siblings like a kind of sequence. So its worth understanding this.

    In elastic4s, you can just use .fields on any field you want, and then those fields will be combined with the parent to become a multi field. So your example re-written would be.

      client.execute {
        createIndex("foo").mappings(
          mapping("bar").fields(
            textField("baz").fields(
              textField("inner1") analyzer PatternAnalyzer,
              textField("inner2") index NotAnalyzed
            )
          )
        )
      }
    

    Note that as is an alias for fields and I think fields is more readable so I used it here.