Java basics not working for me


i am trying out elasticsearch with the java api, but i dont get it to work. I can index documents, but searching for them does not work. I tried termQuery(), termsQuery() and matchQuery(). But documents are never returned.

What is wrong in the code below?

Kind regards

 final Client client = TransportClient.builder().build()
		        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
		client.admin().indices().create(new CreateIndexRequest("myindex")).actionGet();

		final XContentBuilder product1 = XContentFactory.jsonBuilder().prettyPrint()
		        	.field("id", "prod1")
			        .field("name", "prod1")
			        .field("productUrl", "man-prod1")
			        .field("price", "9.99")

		final XContentBuilder product2 = XContentFactory.jsonBuilder().prettyPrint()
	        		.field("id", "prod2")
			        .field("name", "prod2")
			        .field("productUrl", "man-prod2")
			        .field("price", "19.99")
		IndexResponse response1 = client.prepareIndex("myindex", "products", "prod1")
		System.out.println(response1.isCreated()); // gives true
		IndexResponse response2 = client.prepareIndex("myindex", "products", "prod2")
		System.out.println(response2.isCreated()); // gives true
		final SearchResponse searchResponse =  client.prepareSearch("myindex")
		        .setQuery(QueryBuilders.termQuery("productUrl", "man-prod2"))
		final SearchHit[] searchHits = searchResponse.getHits().getHits();

You need to refresh the index before being able to search for docs you just indexed.

Don't do that in PROD but just in the context of tests.

Also be careful with your analyzers. I think that your field productUrl is indexed as man, prod2 so a term query with man-prod2 won't match.

Thanks for the answer. After indexing the two documents, i do a

now termQuery() and matchQuery() give me the two documents.

so i should refresh the index always after indexing, right ?

should i also refresh the index after values of a document were modified?

Next step is to mark the productUrl as not indexed, so i don't want run into the issue you've described.

kind regards

so i should refresh the index always after indexing, right ?

Refreshes take place automatically every few seconds (configurable), but if you want recently indexed documents to be immediately searchable (like on your case above) an explicit refresh is necessary to guarantee that searches will include the recently indexed document(s).

thanks for answer.

so a refresh is also not neccessary after modification of data...