Skip to content
kimchy edited this page Feb 5, 2011 · 2 revisions

The Java API allows to interact with an elasticsearch cluster using Java. It forms the basis of elasticsearch API, so everything exposed there is also available in Java.

All interaction with the cluster to perform operations are done by obtaining a Client first. The Client lifecycle should be the same as the application lifecycle.

Maven Repository

p. The maven repository is hosted on Sonatype, with both a releases repo and a snapshots repo.

Anatomy of an API

The API is asynchronous in nature. All APIs follow the following format:

client.prepareXXX()
      .setYYY(...)
      .setXXX(...)
      .execute()
      .actionGet()

The execute can have a listener passed to it (in which case there is no need to call actionGet), or, when using without a listener, will return a future. The future can have a listener registered with it or used to execute a blocking get.

For example, here is a sample Index API execution:

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 Elastic Search")
                    .endObject()
                  )
        .execute()
        .actionGet();

Query DSL

The Query DSL can be fully expressed using QueryBuilders and FilterBuilders. Here are some examples:

import static org.elasticsearch.index.query.xcontent.FilterBuilders.*;
import static org.elasticsearch.index.query.xcontent.QueryBuilders.*;

QueryBuilder qb1 = termQuery("name", "kimchy");

QueryBuilder qb2 = boolQuery()
                    .must(termQuery("content", "test1"))
                    .must(termQuery("content", "test4"))
                    .mustNot(termQuery("content", "test2"))
                    .should(termQuery("content", "test3"));

QueryBuilder qb3 = filteredQuery(
            termQuery("name.first", "shay"), 
            rangeFilter("age")
                .from(23)
                .to(54)
                .includeLower(true)
                .includeUpper(false)
            );
Clone this wiki locally