Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElasticSearch equivalent of Solr getBeans

I'm trying to go from Solr to Elasticsearch, I have been converting some classes that I had working with Solr to Elasticsearch but right now I'm stuck in this.

In Solr I used to have:

QueryResponse response = getServer().query(myQuery);
List<MyClass> result = response.getBeans(MyClass.class);

and that was it, I got a List with MyClass objects that I could use, but I haven't found an equivalent for getBeans in ElasticSearch java API, is there something similar or I have to get the result source with

searchHit.getSourceAsString();

or

searchHit.getSource();

and parse the result to create my own bean?

Any help or pointer in the right direction will be very appreciated.

Thanks.

like image 476
im8bit Avatar asked Feb 25 '13 15:02

im8bit


1 Answers

Elasticsearch allows you to read the whole source in different formats, among which the most interesting ones for you are:

  • as a String through the SearchHit#sourceAsString method
  • as a Map<String, Object> through the SearchHit#sourceAsMap method

Note that the source is not the only way to get results back: you can also ask for some specific fields which can either be stored in lucene or automatically loaded from the source when not stored. Then you would get back a Map<String, SearchHitField> through the SearchHit#fields method.

Elasticsearch is simply more json oriented than Solr, providing highly optimized ways to read and produce json objects. As far as I know there is no out-of-the-box way to get a Java object back directly from the SearchHit using the Java API. There used to be the interesting osem project which seems to do something similar to what you're looking for, but it doesn't seem to be maintained anymore.

There are different libraries to transform a Json object into a Java object if you really need that. elasticsearch itself uses Jackson internally.

Otherwise, an alternative to the Java API is the Jest client, which does allow to both index and retrieve documents as POJOs. But in this case you would be using an external library which sends Rest calls to elasticsearch instead of the Java API which are pretty powerful.On the other hand you wouldn't need the whole elasticsearch as dependency.

like image 157
javanna Avatar answered Nov 07 '22 20:11

javanna