Case 1:
{
"query": {
"match": {
"company_name": "DEFG"
}
}
}
Case 1 Java:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest = new SearchRequest("company");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchQuery("company_name", "DEFG"));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse.toString());
Case 2:
You can achived this using script_field.
You need to pass same query to the if condition as well. so it will generate new field with only address which is matched with your query.
{
"_source": {
"excludes": "name"
},
"query": {
"match": {
"companyaddress.address3": "smp1"
}
},
"script_fields": {
"address": {
"script": {
"lang": "painless",
"source": """
List li = new ArrayList();
if(params['_source']['companyaddress'] != null)
{
for(p in params['_source']['companyaddress'])
{
if( p.address3 == 'smp1')
li.add(p);
}
}
return li;
"""
}
}
}
}
Case 2 Response:
Please see the fields tag which have address which is matching to the query.
{
"_index" : "company",
"_type" : "_doc",
"_id" : "101",
"_score" : 0.6548753,
"_source" : {
"companyaddress" : [
{
"address3" : "smp1",
"main_phone1" : "1"
},
{
"address3" : "chtp2",
"main_phone1" : "2"
},
{
"address3" : "gmd",
"main_phone1" : "3"
},
{
"address3" : "tste",
"main_phone1" : "4"
}
],
"company_id" : "3",
"company_name" : "DEFG"
},
"fields" : {
"address" : [
{
"address3" : "smp1",
"main_phone1" : "1"
}
]
}
}
Case 2 Java:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest = new SearchRequest("company");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchQuery("companyaddress.address3", "smp1"));
Map<String, Object> param = new HashMap<String, Object>();
String source = "List li = new ArrayList();if(params['_source']['companyaddress'] != null){for(p in params['_source']['companyaddress']){if( p.address3 == 'smp1')li.add(p);}}return li;";
Script script = new Script(ScriptType.INLINE, "painless", source, param);
sourceBuilder.scriptField("address", script);
sourceBuilder.fetchSource(true);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse.toString());
client.close();