Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created May 26, 2015 05:34
Show Gist options
  • Save fearofcode/63aca07f84c3a82c83cd to your computer and use it in GitHub Desktop.
Save fearofcode/63aca07f84c3a82c83cd to your computer and use it in GitHub Desktop.
Simple Elasticsearch usage
package org.wkh.learningelasticsearch;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.node.Node;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import java.util.Date;
import static org.elasticsearch.node.NodeBuilder.*;
import static org.elasticsearch.common.xcontent.XContentFactory.*;
public class LearningElasticSearch {
public static void main(String[] args) throws Exception {
Node node = nodeBuilder().node();
Client client = node.client();
IndexResponse response = client.prepareIndex("twitter", "tweet")
.setSource(jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "warren loves Rosalind")
.endObject()
)
.execute()
.actionGet();
System.out.println(response.isCreated());
SearchResponse searchResponse = client
.prepareSearch("twitter")
.setQuery(QueryBuilders.matchQuery("message", "Rosalind"))
.execute()
.actionGet();
SearchHits hits = searchResponse.getHits();
System.out.println(hits.totalHits());
for(SearchHit hit : hits.getHits()) {
System.out.println("hit: " + hit.getSource().get("message"));
}
node.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment