| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205 | [[index_]]== Index APIThe index API allows one to index a typed JSON document into a specificindex and make it searchable.[[generate]]=== Generate JSON documentThere are different way of generating JSON document:* Manually (aka do it yourself) using native `byte[]` or as a `String`* Using `Map` that will be automatically converted to its JSONequivalent* Using a third party library to serialize your beans such ashttp://wiki.fasterxml.com/JacksonHome[Jackson]* Using built-in helpers XContentFactory.jsonBuilder()Internally, each type is converted to `byte[]` (so a String is convertedto a `byte[]`). Therefore, if the object is in this form already, thenuse it. The `jsonBuilder` is highly optimized JSON generator thatdirectly constructs a `byte[]`.==== Do It YourselfNothing really difficult here but note that you will have to encodedates regarding to the{ref}/mapping-date-format.html[Date Format].[source,java]--------------------------------------------------String json = "{" +        "\"user\":\"kimchy\"," +        "\"postDate\":\"2013-01-30\"," +        "\"message\":\"trying out Elasticsearch\"," +    "}";--------------------------------------------------[[using-map]]==== Using MapMap is a key:values pair collection. It represents very well a JSONstructure:[source,java]--------------------------------------------------Map<String, Object> json = new HashMap<String, Object>();json.put("user","kimchy");json.put("postDate",new Date());json.put("message","trying out Elasticsearch");--------------------------------------------------[[beans]]==== Serialize your beansElasticsearch already use Jackson but shade it under`org.elasticsearch.common.jackson` package. + So, you can add your own Jackson version in your `pom.xml` file or inyour classpath. See http://wiki.fasterxml.com/JacksonDownload[JacksonDownload Page].For example:[source,xml]--------------------------------------------------<dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>2.1.3</version></dependency>--------------------------------------------------Then, you can start serializing your beans to JSON:[source,java]--------------------------------------------------import com.fasterxml.jackson.databind.*;// instance a json mapperObjectMapper mapper = new ObjectMapper(); // create once, reuse// generate jsonString json = mapper.writeValueAsString(yourbeaninstance);--------------------------------------------------[[helpers]]==== Use Elasticsearch helpersElasticsearch provides built-in helpers to generate JSON content.[source,java]--------------------------------------------------import static org.elasticsearch.common.xcontent.XContentFactory.*;XContentBuilder builder = jsonBuilder()    .startObject()        .field("user", "kimchy")        .field("postDate", new Date())        .field("message", "trying out Elasticsearch")    .endObject()--------------------------------------------------Note that you can also add arrays with `startArray(String)` and`endArray()` methods. By the way, `field` method + accept many object types. You can pass directly numbers, dates and evenother XContentBuilder objects.If you need to see the generated JSON content, you can use the@string()@method.[source,java]--------------------------------------------------String json = builder.string();--------------------------------------------------[[index-doc]]=== Index documentThe following example indexes a JSON document into an index calledtwitter, under a type called tweet, with id valued 1:[source,java]--------------------------------------------------import static org.elasticsearch.common.xcontent.XContentFactory.*;IndexResponse response = client.prepareIndex("twitter", "tweet", "1")        .setSource(jsonBuilder()                    .startObject()                        .field("user", "kimchy")                        .field("postDate", new Date())                        .field("message", "trying out Elasticsearch")                    .endObject()                  )        .execute()        .actionGet();--------------------------------------------------Note that you can also index your documents as JSON String and that youdon't have to give an ID:[source,java]--------------------------------------------------String json = "{" +        "\"user\":\"kimchy\"," +        "\"postDate\":\"2013-01-30\"," +        "\"message\":\"trying out Elasticsearch\"," +    "}";IndexResponse response = client.prepareIndex("twitter", "tweet")        .setSource(json)        .execute()        .actionGet();--------------------------------------------------`IndexResponse` object will give you report:[source,java]--------------------------------------------------// Index nameString _index = response.index();// Type nameString _type = response.type();// Document ID (generated or not)String _id = response.id();// Version (if it's the first time you index this document, you will get: 1)long _version = response.version();--------------------------------------------------If you use percolation while indexing, `IndexResponse` object will giveyou percolator that have matched:[source,java]--------------------------------------------------IndexResponse response = client.prepareIndex("twitter", "tweet", "1")        .setSource(json)        .execute()        .actionGet();List<String> matches = response.matches();--------------------------------------------------For more information on the index operation, check out the REST{ref}/docs-index_.html[index] docs.=== Operation ThreadingThe index API allows to set the threading model the operation will beperformed when the actual execution of the API is performed on the samenode (the API is executed on a shard that is allocated on the sameserver).The options are to execute the operation on a different thread, or toexecute it on the calling thread (note that the API is still async). Bydefault, `operationThreaded` is set to `true` which means the operationis executed on a different thread.
 |