Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElasticSearch full text search using Java API

I've recently started exploring the world of search, and am trying to use ES as the index for my MongoDB. I've managed to integrate them successfully, but I find the search API rather complex and confusing. The Java API is not too helpful either. I am able to find exact matches, but how do I do full-text searches? Here is my code:

Settings settings = ImmutableSettings.settingsBuilder()
    .put("cluster.name", "elasticsearch").build();
Client client = new TransportClient(settings)
    .addTransportAddress(new InetSocketTransportAddress("host-ip", 9300));
SearchResponse response = client.prepareSearch("mongoindex")
    .setSearchType(SearchType.QUERY_AND_FETCH)
    .setQuery(termQuery("name", "*name*"))
    .setFrom(0).setSize(60).setExplain(true)
    .execute()
    .actionGet();

I have no problems finding "name":"testname" using .setQuery(termQuery("name", "testname")), but "name":"this is a test name" doesn't work with the above example. What am I doing wrong?

like image 914
Wei Hao Avatar asked Jan 12 '13 19:01

Wei Hao


1 Answers

After crawling the Internet for hours, I've managed to figure it out, with some help from the javadocs. The most important is the interface *QueryBuilder*, and its implementing classes. I used FieldQueryBuilder for my query, which in shown in the setQuery method below.

SearchResponse response = client.prepareSearch("mongoindex")
    .setSearchType(SearchType.QUERY_AND_FETCH)
    .setQuery(fieldQuery("name", "test name"))
    .setFrom(0).setSize(60).setExplain(true)
    .execute()
    .actionGet();
SearchHit[] results = response.getHits().getHits();
for (SearchHit hit : results) {
  System.out.println(hit.getId());    //prints out the id of the document
  Map<String,Object> result = hit.getSource();   //the retrieved document
}

With the resulting Map object, you can simply call the get method to retrieve the relevant data.

like image 137
Wei Hao Avatar answered Oct 15 '22 02:10

Wei Hao