user3077045
user3077045

Reputation: 25

How Can I Index and Search with Elasticsearch

IndexResponse response = client.prepareIndex("face", "book","1")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("name", "kimchy")
                        .field("postDate", "2010-03-01")
                        .field("message", "trying out Elastic Search")
                        .endObject()
                )
                .execute()
                .actionGet();
String index = response.getIndex(); // index : "face"

SearchResponse r = client.prepareSearch("face")
    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
    .setQuery(QueryBuilders.termQuery("name","kimchy"))
    .setFrom(0).setSize(60).setExplain(true)
    .execute()
    .actionGet();
      System.out.println(r);
      SearchHit[] hits = r.getHits().getHits();
      System.out.println(hits.length); // 0 Hits
      for (SearchHit searchHit : hits) {
      // no hits no data
      }

How can I fix this , where is the problem here ? My each attempts gives 0 hits.I tried everything but i could not fix.I will be happy if someone help me to fix this code.If I write prepareIndex("twitter", "tweet","1") and client.prepareIndex("twitter", "tweet","1") it gives me some results but i think this is default result.I want to search specific word which i want.

Upvotes: 0

Views: 585

Answers (2)

javanna
javanna

Reputation: 60195

The problem is that search works in near real-time, which means that a refresh needs to happen after you indexed a document in order for it to be available for search.

A refresh automatically happens every second by default, but in your test you need to either call refresh manually to make sure the document is found, or switch to using the get api, which works in real-time, to make sure the document is present, getting it back by id.

In case you add refresh, you can either call the refresh api or add the refresh flag to the index operation, so that a refresh will happen after the document is indexed. Just remember that this is good practice while testing, but in production your code shouldn't call refresh manually, just let the automatic refresh kick in every second.

Upvotes: 1

mconlin
mconlin

Reputation: 8733

Try adding

.setRefresh(true)

To your client.prepareIndex call

Upvotes: 0

Related Questions