I'm new to elasticsearch and Java.
I have a JSON object like
{
"keyword":null,
"size":[],
"matchResults":
{
"Data": ["first" "Second"]
},
}
I want to search against "matchResults" field and expect output like below:
"Data" : "first"
"Data" : "Second"
"Data" : "first Second"
"Data" : "Second friend"
for getting these results I'm using matchQuery in Java code like this,
Map<String, List<String>> matchResults = request.getMatchResults();
if (matchResults != null) {
for (Map.Entry<String, List<String>> filter : matchResults.entrySet()) {
logger.info("key is" );
List<String> values = filter.getValue();
if (values != null) {
query = query.filter(QueryBuilders.matchQuery(filter.getKey(), values));
}
}
}
But this gives below error
{
"messages": [
"{\"root_cause\":[{\"type\":\"parsing_exception\",\"reason\":\"[match] unknown token [START_ARRAY] after [query]\",\"line\":9,\"col\":23}],\"type\":\"parsing_exception\",\"reason\":\"[match] unknown token [START_ARRAY] after [query]\",\"line\":9,\"col\":23}"
],
"data": null,
"message": "{\"root_cause\":[{\"type\":\"parsing_exception\",\"reason\":\"[match] unknown token [START_ARRAY] after [query]\",\"line\":9,\"col\":23}],\"type\":\"parsing_exception\",\"reason\":\"[match] unknown token [START_ARRAY] after [query]\",\"line\":9,\"col\":23}"
}
Not sure what is causing this.
Related
I am trying to update the phone number using the below query, but I am getting "mapper_parsing_exception. Refer the code attached below.
Query:
POST /ps/_update/alOKenkBHofR-Ip1hPcv
{
"doc": {
"ph": {
"na": null,
"nu": "877842376",
"cc": "91",
"ex": null,
"pt": "M"
},
"mdt": "20210615T044700.714Z"
}
Response:
{
"error" : {
"root_cause" : [
{
"type" : "mapper_parsing_exception",
"reason" : "failed to parse field [ph] of type [text] in document with id 'alOKenkBHofR-Ip1hPcv'. Preview of field's value: '{cc=91, na=null, ex=null, pt=M, nu=877842376}'"
}
],
"type" : "mapper_parsing_exception",
"reason" : "failed to parse field [ph] of type [text] in document with id 'alOKenkBHofR-Ip1hPcv'. Preview of field's value: '{cc=91, na=null, ex=null, pt=M, nu=877842376}'",
"caused_by" : {
"type" : "illegal_state_exception",
"reason" : "Can't get text on a START_OBJECT at 1:3558"
}
},
"status" : 400
}
// code
Document document = Document.create();
Map<String, Object> map = new Phone.ToMap().convert((Phone) value);
document.put(key, map);
UpdateQuery updateQuery = UpdateQuery.builder(id).withDocument(document).build();
UpdateResponse updateResponse = operations.update(updateQuery, indexCoordinates());
Result result = updateResponse.getResult();
Your ph is part of bi object so for updating your document you should do this query:
POST /ps/_update/alOKenkBHofR-Ip1hPcv
{
"doc": {
"bi"{
"ph": {
"na": null,
"nu": "877842376",
"cc": "91",
"ex": null,
"pt": "M"
}
},
"mdt": "20210615T044700.714Z"
}
I am testing REST api. Below is my JSON response.
[ {
"id" : 1,
"name" : "Chattagram"
}, {
"id" : 2,
"name" : "Rajshahi"
}, {
"id" : 3,
"name" : "Khulna"
}, {
"id" : 4,
"name" : "Barisal"
}, {
"id" : 5,
"name" : "Sylhet"
}, {
"id" : 6,
"name" : "Dhaka"
}, {
"id" : 7,
"name" : "Rangpur"
}, {
"id" : 8,
"name" : "Mymensingh"
} ]
I have converted the list into a List of HashMap. I am able to access the name field but when trying to get the id, below exception is happening. I am not understanding why this exception, cause the key is correct. I have given the debug console image, can any one tell me what is the issue and how i can access the id?
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
Source Code :
#Test
public void getEmployees() throws IOException {
final String uri = "http://localhost:8080/public/geocode/divisions";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
restTemplate.getForObject(uri, String.class);
System.out.println(result);
ObjectMapper mapper = new ObjectMapper();
List<Map<String, String>> list = new ArrayList<>();
list = mapper.readValue(result, List.class);
System.out.println(list.get(0));//--------------out put : {id=1, name=Chattagram}
Map<String, String> m = list.get(0);
System.out.println("id : " + m.get("id")); //------------problem line
System.out.println("Name : " + m.get("name")); //------------working fine
System.out.println(list);
}
After setting a break point in the problem line, debug variables :
Try
System.out.println("id : " + Integer.toString(m.get("id"));
Am new to rest assured.Using rest assured am trying to verify data detail is found or not.Here two data details present.Some times it will be 2 or 3 or 5
Am getting response as follows and using java
{
"queryPath": "/api/",
"nId": "f084f5ad24fcfaa9e9faea0",
"statusCode": 707
"statusMessage": "Success",
"results": {
"data": [
{
"id": "10248522500798",
"capabilities": [
"record",
"HDt"
],
"name": "errt2"
},
{
"id": "418143778",
"capabilities": [
"1record",
"HDy"
],
"name": "Livin"
}
]
}
}
code using
JsonPath jsonResponse = new JsonPath(response.asString());
ArrayList<String> list = new ArrayList<String>();
list = jsonResponse.get("results.data"); //
if (list.size() < 1 ) {
SpiceCheck.fail("data not found! " + list.size());
}
Rather than this i wwant to check the data name is null or not also.How can i do that rest assured.
Just so you know you are missing a comma after 707.
To verify that none of the names is null I would parse out the names as a list, then iterate over the names one by one and check that they aren't null.
List<String> names = from(response.asString()).getList("results.data.name");
for(String name : names){
if(name == null){
// error handling code here
}
}
My mongo collection has entries in the following format
{
"myobj" : {
"objList" : [
{ "location" : "Texas" },
{ "location" : "Houston"},
{ "name":"Sam" }
]
},
"category" : "cat1"
}
{
"myobj" :
{
"objList" : [
{ "location" : "Tennesy" },
{ "location" : "NY"},
{ "location" : "SF" }
]
},
"category" : "cat2"
}
I want to extract the "**category**" where location is "Houston". In case of simple JSON object I have to just pass it as query like:
BasicDBObject place = new BasicDBObject();
place.put("location", "Houston");
But in case of nested JSON I don't know how to pass it as a query and get the appropriate category. ie If I pass my location as"Houston" then it should return it's appropriate category "cat1"...i hope my question is clear now....
Ok, you have your documents:
db.coll1.insert({
"myobj" : {
"objList" : [
{ "location" : "Texas" },
{ "location" : "Houston"},
{ "name":"Sam" }
]
},
"category" : "cat1"
})
and
db.coll1.insert({
"myobj" : {
"objList" : [
{ "location" : "Tennesy" },
{ "location" : "Houston"},
{ "location" : "SF" }
]
},
"category" : "cat1"
})
Now you can find what you want using the dot operator:
db.coll1.find({"myobj.objList.location": "Texas"}).pretty() will return one object which has Texas
db.coll1.find({"myobj.objList.location": "SF"}).pretty() will return one object which has SF
db.coll1.find({"myobj.objList.location": "Houston"}).pretty() will return both objects
And now I hope you will be able to write it in Java. I have never used Java, but based on this question you can do something like this. If it will not work, just look how to use dot operator in java driver for mongo:
DBCursor cursor = coll1.find(new BasicDBObject("myobj.objList.location", "Texas"));
P.S. you told, that you wanted to retrieve category. In such a way, you will need to use a projection db.coll1.find({<the query I provided}, {category: 1, _id: 0})
I have JSON File as below which has to be dumped into an ArrayList:
{
"main1" : [
{
"child1" : valueA,
"child2" : valueB,
"child3" : valueC,
},
{
"child1" : value1,
"child3" : value3,
},
],
"main2" : "valueMain2"
}
The element child2 has to be checked if it exists or not and then the value is taken. You can see that it doesn't appear in the second array.
I am using Native JSON (org.JSON)
Java Code is below:
ArrayList<HashMap<String,String>> myList = new ArrayList<HashMap<String,String>>();
JSONObject json = <my_json_object>;
JSONObject getchild2;
JSONArray jArray = <my_json_object>.getJSONArray("main1");
for(int j = 0; j < jArray.length(), j++){
HashMap<String,String> map = new HashMap<String,String>();
map.put("First Value", jArray.getJSONObject(j).getString("child1"));
map.put("Third Value", jArray.getJSONObject(j).getString("child3"));
getchild2 = jArray.getJSONObject(j).getJSONObject("child2");
if(getchild2 == null){
map.put("Second Value", "Some Dummy Value");
} else {
map.put("Second Value", jArray.getJSONObject(j).getString("child2"));
}
myList.add(map);
}
How can I achieve this?
<my_json_object> uses native URL Parsing as I get the HTTP Response of a URL request found here: http://mobisys.in/blog/2012/01/parsing-json-from-url-in-android/
It doesn't work as error is below:
E/AndroidRuntime(664): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Anyway, I got the solution with some Googling:
I re-framed it as,
if (!jArray.getJSONObject(j).has("child2")) {
map.put("Second Value", "N.A");
} else {
map.put("Second Value", jArray.getJSONObject(j).getString("child2"));
}
Creating the JSONObject getchild2 = jArray.getJSONObject(j).getJSONObject("child2"); was rather, unnecessary.
And this works, rather perfectly! Refer this for more details: Checking if exists subObject in JSON
Thanks everyone for the help!
getJSONObject("child2");
Will throw an exception if child2 does not exist. Try this instead:
getchild2 = jArray.getJSONObject(j).optJSONObject("child2");
That way you don't have to catch an exception if child2 doesn't exist and can instead check for null.
Try this:
{"main1" : [{
"id":"1"
"child1" : "valueA",
"child2" : "valueB",
"child3" : "valueC",
}, {
"id":"2"
"child1" : "value1",
"child3" : "value3",
}]
}