How to search with full Json query using Java API

I need to be able to perform searches with the full JSON queries that you would normally use with CURL. How can I do this using the Java API. My current approach is not working:

  1. A sample query (which works directly using CURL)

    {"query":{"match":{"abstract":"A 58-year-old African-American woman presents to the ER with episodic pressing/burning anterior chest pain that began two days earlier for the first time in her life. The pain started while she was walking, radiates to the back, and is accompanied by nausea, diaphoresis and mild dyspnea, but is not increased on inspiration. The latest episode of pain ended half an hour prior to her arrival. She is known to have hypertension and obesity. She denies smoking, diabetes, hypercholesterolemia, or a family history of heart disease. She currently takes no medications. Physical examination is normal. The EKG shows nonspecific changes."}}}

  2. The API method I am trying to use now where queryDef is the JSON query above:

     	SearchResponse response;		
     try {
     	 response = _myClient.prepareSearch(indexToSearch)
     	        .setTypes(docType)
     	        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
     	        .setQuery(QueryBuilders.wrapperQuery(queryDef))                 // Query
     	        .setFrom(0).setSize(maxNumberToGet).setExplain(true)
     	        .execute()
     	        .actionGet();
    
     } catch (Exception e) {
     	System.out.println("Error performing search: " + e.getLocalizedMessage());
     	return null;
     }
    
  3. The error results are: all shards failed

How can I run a query using the API where I have specified the full query?

I seem to have got it working with:

		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	QueryBuilder qb = QueryBuilders.simpleQueryStringQuery(queryDef);
	searchSourceBuilder.query(qb);

   SearchResponse response;		
	try {
		 response = _myClient.prepareSearch(indexToSearch)
		        .setTypes(docType)
		        .setSource(searchSourceBuilder)
		        .setFrom(0).setSize(maxNumberToGet).setExplain(true)
		        .execute()
		        .actionGet();
	} catch (Exception e) {
		System.out.println("Error performing search on index[" + indexToSearch + "] and docType[" + docType + "] using query[" + queryDef + "]. Error is: " + e.getLocalizedMessage());
		return null;
	}

Will have to test across different queries.

This is actually incorrect and doesn't work. The best solution is to use the low level java REST api client.

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