After creating an index, the next step is to add some mappings to it. We have already seen how to include a mapping via the REST API in Chapter 4, Basic Operations. In this recipe, we will see how to manage mappings via a native client.
You need an up-and-running Elasticsearch installation, as we described in the Downloading and installing Elasticsearch recipe in Chapter 2, Downloading and Setup.
A Maven tool or an IDE that supports Scala programming, such as Eclipse (ScalaIDE) or IntelliJ IDEA, with the Scala plugin should be installed.
The code of this recipe can be found in the chapter_15/elastic4s_sample
file and the referred class is MappingExample
.
In the following code, we add a mytype
mapping to a myindex
index via the native client:
package com.packtpub import com.sksamuel.elastic4s.ElasticDsl._
object MappingExample extends App with ElasticSearchClientTrait{ val indexName="myindex" if(client.execute{ indexExists(indexName)}.await.isExists){ client.execute{ deleteIndex(indexName)}.await }
mytype
mapping:client.execute{ createIndex(indexName) shards 1 replicas 0 mappings ( mapping("mytype")as (textField("name").termVector ("with_positions_offsets").stored(true) ) ) }.await Thread.sleep(2000)
putMapping
call:client.execute{ putMapping(indexName / "mytype").as( keywordField("tag") ) }.await
val myMapping=client.execute{ getMapping(indexName / "mytype") }.await
tag
field:val tagMapping=myMapping.fieldFor(indexName / "mytype", "tag") println(tagMapping)
client.execute(deleteIndex(indexName)).await
//we need to close the client to free resources client.close(); } }
Before executing a mapping operation, a client must be available.
We can include the mapping during index creation via the mappings
method in the createIndex
builder:
createIndex(indexName) shards 1 replicas 0 mappings ( mapping("mytype")as ( textField("name").termVector("with_positions_offsets").stored(true) ) )
If we forgot to put a field in the mapping, or during our application life we need to add a new field, putMapping
can be called with the new field or a new complete type mapping.
putMapping(indexName / "mytype").as( keywordField("tag") )
In this way, if the type exists it is updated; otherwise, it is created.
In the admin console, or to check our index types stored in mappings, we need to retrieve them from the cluster state. The method that we have already seen is the getMapping
method:
val myMapping=client.execute{ getMapping(indexName / "mytype") }.await
The returned mapping object also has some help methods to check the mappings for a single field via the fieldFor
call:
val tagMapping=myMapping.fieldFor(indexName / "mytype", "tag") println(tagMapping)
The returned value is a Map[String, Any]
.
18.226.185.196