Skip to content

Instantly share code, notes, and snippets.

@keerts
Created February 1, 2012 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save keerts/1717488 to your computer and use it in GitHub Desktop.
Save keerts/1717488 to your computer and use it in GitHub Desktop.
Unit test for evaluating elasticsearch
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