Last active
December 30, 2015 20:39
-
-
Save FestivalBobcats/7882583 to your computer and use it in GitHub Desktop.
Connecting to Qbox.io Elasticsearch cluster with the Java TransportClient.
This file contains 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
import org.elasticsearch.action.bulk.BulkItemResponse; | |
import org.elasticsearch.action.bulk.BulkRequestBuilder; | |
import org.elasticsearch.action.bulk.BulkResponse; | |
import org.elasticsearch.action.search.SearchResponse; | |
import org.elasticsearch.client.Client; | |
import org.elasticsearch.client.transport.TransportClient; | |
import org.elasticsearch.common.settings.ImmutableSettings; | |
import org.elasticsearch.common.settings.Settings; | |
import org.elasticsearch.common.transport.InetSocketTransportAddress; | |
import org.elasticsearch.index.query.QueryBuilders; | |
public class TransportTest { | |
public static void main(String[] args) { | |
Settings settings = ImmutableSettings.settingsBuilder() | |
.put("cluster.name", "your-cluster-name") | |
.build(); | |
Client client = new TransportClient(settings) | |
.addTransportAddress(new InetSocketTransportAddress("your-node-1-endpoint.qbox.io", 9300)) | |
.addTransportAddress(new InetSocketTransportAddress("your-node-2-endpoint.qbox.io", 9300)); | |
String doc1 = "{\"name\":\"Product One\",\"price\":14.99}"; | |
String doc2 = "{\"name\":\"Product Two\",\"price\":24.99}"; | |
String doc3 = "{\"name\":\"Product Three\",\"price\":34.99}"; | |
String doc4 = "{\"name\":\"Product Four\",\"price\":44.99}"; | |
String doc5 = "{\"name\":\"Product Five\",\"price\":54.99}"; | |
BulkRequestBuilder bulkRequest = client.prepareBulk(); | |
bulkRequest.add(client.prepareIndex("products", "product", "1").setSource(doc1)); | |
bulkRequest.add(client.prepareIndex("products", "product", "2").setSource(doc2)); | |
bulkRequest.add(client.prepareIndex("products", "product", "3").setSource(doc3)); | |
bulkRequest.add(client.prepareIndex("products", "product", "4").setSource(doc4)); | |
bulkRequest.add(client.prepareIndex("products", "product", "5").setSource(doc5)); | |
BulkResponse bulkResponse = bulkRequest.get(); | |
if (bulkResponse.hasFailures()) { | |
for (BulkItemResponse response : bulkResponse.getItems()) { | |
System.out.print("Failure:" + response.getFailureMessage()); | |
} | |
} | |
client.admin().indices().prepareRefresh("products").get(); | |
SearchResponse response = client.prepareSearch("products") | |
.setQuery(QueryBuilders.matchQuery("name", "product *")) | |
.get(); | |
System.out.print("Found " + response.getHits().totalHits() + " results."); | |
client.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment