Error with elasticsearch and java


(salma) #1

Hi,
I need to extract data from elasticsearch with java but this return an main exception

while(true){
				TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
						   .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
				SearchRequestBuilder srb2 = client
					    .prepareSearch().setQuery(QueryBuilders.matchQuery("Time",0)).setSize(1);
				
				MultiSearchResponse sr = client.prepareMultiSearch().add(srb2).get();
				
				
				for (MultiSearchResponse.Item item : sr.getResponses()) {
					
					SearchResponse response = item.getResponse();
					for(int i = 0; i < response.getHits().getTotalHits(); i ++){
					SearchHit sHit = response.getHits().getAt(i);
					SearchHits sHits = response.getHits();
					SearchHit[] sHitList = response.getHits().getHits();
					for(SearchHit sHitItem : sHitList){
						System.out.println("sHitItem ==> "+sHitItem.getSourceAsString());
						Data data = ConvertConfig.ConvertToData(sHitItem.getSourceAsString());
						data.setId(sHitItem.getId());
						RowData row = Prediction.predictionData(data);
						System.out.print("\t "+row.get("Classe").toString());
					}
					}
				}

				
				client.close();
				
			}

error:

Exception in thread "main" Class probabilities: 0java.lang.ArrayIndexOutOfBoundsException: 1
at org.elasticsearch.search.SearchHits.getAt(SearchHits.java:117)
at com.backend.project.BackendProject.main(BackendProject.java:57)

any help please
thank you


(David Pilato) #2
while(true){
}

OMG! Why are you doing this?
At least create your client outside of the loop.
And close it after.

Then be aware that even though elasticsearch tells you you have 1 000 000 of documents which are matching (getTotalHits()) , it will send you back only the 10 first most relevant documents.

So you should not iterate like this:

for(int i = 0; i < response.getHits().getTotalHits(); i ++)

(salma) #3

Hi David ,
I use a "getTotalHits" because i need to find all id by field_time for example when time = 0 the return is total hits when time=0


(David Pilato) #4

You need to use the scroll API as I said.

See https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search-scrolling.html


(system) #5

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.