Created
February 1, 2012 15:18
-
-
Save keerts/1717488 to your computer and use it in GitHub Desktop.
Unit test for evaluating elasticsearch
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
package nl.avisi.langur.search; | |
import static org.elasticsearch.common.xcontent.XContentFactory.*; | |
import static org.elasticsearch.index.query.QueryBuilders.*; | |
import static org.elasticsearch.node.NodeBuilder.*; | |
import static org.hamcrest.Matchers.*; | |
import static org.junit.Assert.*; | |
import java.io.IOException; | |
import org.elasticsearch.action.search.SearchResponse; | |
import org.elasticsearch.client.Client; | |
import org.elasticsearch.client.Requests; | |
import org.elasticsearch.node.Node; | |
import org.junit.Test; | |
public class ElasticSearchEvaluation { | |
private static final String INDEX_NAME = "keys"; | |
@Test | |
public void testES() throws Exception { | |
Node server = startServer(); | |
checkForOrOtherWiseCreateIndex(server); | |
Client client = server.client(); | |
indexSomeData(client); | |
SearchResponse response = client.prepareSearch(INDEX_NAME) | |
.setQuery(termQuery("name", "title")) | |
.execute() | |
.actionGet(); | |
assertThat(response.hits().totalHits(), equalTo(1l)); | |
} | |
private void checkForOrOtherWiseCreateIndex(Node server) { | |
if (!server.client().admin().indices().exists(Requests.indicesExistsRequest(INDEX_NAME)).actionGet().exists()) { | |
server.client() | |
.admin() | |
.indices() | |
.create(Requests.createIndexRequest(INDEX_NAME)) | |
.actionGet(); | |
} | |
} | |
private Node startServer() { | |
Node server = nodeBuilder().build(); | |
server.start(); | |
return server; | |
} | |
private void indexSomeData(Client client) throws IOException { | |
indexAKey(client, "k2", "title"); | |
indexAKey(client, "k3", "footer"); | |
indexAKey(client, "k4", "header"); | |
client.admin().indices().prepareRefresh().execute().actionGet(); | |
} | |
private void indexAKey(Client client, String id, String keyName) throws IOException { | |
client.prepareIndex(INDEX_NAME, "key", id) | |
.setSource(jsonBuilder() | |
.startObject() | |
.field("name", keyName) | |
.endObject()) | |
.execute() | |
.actionGet(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment