Starting with ElasticSearch
Starting with ElasticSearch
ElasticSearch is a distributed, RESTful search server based on Apache Lucene. The important features of it are listed below:
- Real time data
- RESTful API
- Distributed
- Multi-tenancy
- Document oriented
- Schema free
- Per-operation persistence
- Built on top of Apache Lucene
- High availability
- Full text search
- Conflict management
More detailed information about ElasticSearch can be found at
ElasticSearch.org
A small example program to add, retrieve and search for documents in ES is given below:
package com.rishav.es;
import static org.elasticsearch.node.NodeBuilder.*;
import java.io.IOException;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.node.Node;
import org.elasticsearch.client.Client;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import static org.elasticsearch.common.xcontent.XContentFactory.*;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.FilterBuilders.*;
import org.elasticsearch.index.query.QueryBuilders.*;
public class esConnect {
// on startup
public static void main (String args[]) throws IOException{
// create a client for ElasticSearch running on localhost listening to port 9300
Node node = nodeBuilder().node();
Client client = new TransportClient().addTransportAddress(
new InetSocketTransportAddress("localhost",9300));
// add some record
IndexResponse iresponse = client.prepareIndex("testindex", "tweets", "1")
.setSource(jsonBuilder()
.startObject()
.field("user", "rishav")
.field("postDate", "2013-01-30")
.field("message", "trying out Elastic Search")
.endObject()
)
.execute()
.actionGet();
// retrieve record based on id
GetResponse gresponse = client.prepareGet("testindex", "tweets", "1")
.execute().actionGet();
System.out.println(gresponse.getSourceAsString());
// search for a record based on below filters
SearchResponse sresponse = client.prepareSearch("testindex").
setSearchType(SearchType.DFS_QUERY_THEN_FETCH).
setQuery(QueryBuilders.termQuery("user", "rishav")). // query
setFilter(FilterBuilders.termFilter("message", "out")).
execute().
actionGet();
System.out.println(sresponse.getHits());
// shutdown client
client.close();
}
}
No comments:
Post a Comment