9

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?

1
  • that's just the database that i'm using. Commented Jan 12, 2013 at 20:12

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

It looks like termQuery in elasticsearch uses Lucence for it's search syntax. According to the Lucene docs the "*" wildcard is not allowed as the first term of a search.

4 Comments

if that is the case, how could i search for a phrase (or substring) within text?
I would guess using a query_string elasticsearch.org/guide/reference/query-dsl/…
Unfortunately, that is not in Java, which is really the crux of my question, as I am using the Java API. I've seen the link but I can't translate it into Java.
0

Better to look at [wildcard Query] (http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.