0

I am trying to replicate a in SQL query in elastic search... something similar to select * from products where id in ('123, '345');

I have something like the below -

Set<String> searchIds = new HashSet<String>();
searchIds.add("123");
searchIds.add("456");

response = client.prepareSearch("id_index")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.termsQuery("product_id", searchIds))
                .setFrom(0).setSize(50).setExplain(false)
                .execute().actionGet();
hits = response.getHits();
hits.forEach((h) -> {
    h.getSource().entrySet().stream().forEach((e)->{
        System.out.println(e.getKey()+" : "+String.valueOf(e.getValue()).replace("\n", "").replace("\t", ""));
    });
});
System.out.println("Response : "+response.toString());

The response I am getting from the last System.out.println is as follows,

Response : {
  "took" : 14,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

I know for sure there are two products with product id's 123 and 345 as I was able to see them via Kibana. But the above code returns no hits. Am I replicating the SQL IN query in the right way?

g0c00l.g33k
  • 2,458
  • 2
  • 31
  • 41
  • 1
    What do you get when sending this to your ES: `curl -XGET localhost:9200/id_index/_search -d '{"query":{"terms":{"product_id":["123", "456"]}}}'` ? – Val Mar 22 '16 at 08:40
  • @Val I tested it with CURL even before I posted the question, I do get two products one with product_id 123 and another with product_id 456... Thanks – g0c00l.g33k Mar 22 '16 at 08:59
  • 1
    If I'm not mistaken, shouldn't it be `hits = response.getHits().getHits()` instead of `hits = response.getHits()`? – Val Mar 22 '16 at 09:05
  • @Val I just added a `System.out.println` at the end of it to make sure and I have also updated the question with what I got printed from it .. – g0c00l.g33k Mar 22 '16 at 09:16
  • And you're sure your client hits the right ES server? – Val Mar 22 '16 at 09:18
  • @Val Yes, I am sure on that - Just to make sure I am getting it right - does it mean I am doing the query building the expected way? – g0c00l.g33k Mar 22 '16 at 09:20
  • Yes, seems correct to me as far as I can tell... except for my `getHits()` comment. – Val Mar 22 '16 at 09:22
  • @Val, double checked the server I am hitting, CURL way of getting results with the code pasted above.. It looks fine.. I am not sure if I am missing something..do I have to use another kind of querybuilder? – g0c00l.g33k Mar 23 '16 at 02:33

0 Answers0