Created
May 26, 2015 05:34
-
-
Save fearofcode/63aca07f84c3a82c83cd to your computer and use it in GitHub Desktop.
Simple Elasticsearch usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/query-dsl-queries.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html