Get root element using jsonpath based on sub elements condition - java

I am working with the Jayway JsonPath library to obtain the correct 'id' from below JSON where my phoneNumbers type is 'iPhone'.
In general, I would like to know how to find something from the root element of a block when a specific condition is specified in the sub-JSON objects.
I tried below expressions that select the block associated with iPhone type and also a list of ids respectively, but I am not able to get to the root element id belonging to the JSON object where my phone type is iPhone. Can someone please guide me? I need to get the id as 1 for this question.
To get the list of ids: $[*].id
To get the json object corresponding to iPhone type: $[*].phoneNumbers[?(#.type=='iPhone')]
[
{
"id": "1",
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
},
{
"id": "2",
"phoneNumbers": [
{
"type": "x",
"number": "0123-4567-8888"
},
{
"type": "y",
"number": "0123-4567-8910"
}
]
}
]

I think you want your expression to look deeper.
First, find the objects that have an iPhone in the phone numbers list. Then just select the IDs.
Try $[?(#.phoneNumbers[*].type=="iPhone")].id.
Edit
It looks like the Java JsonPath library (I think you're using this) supports a number of functions. It doesn't list a contains(), but you might try the anyof operator:
$[?(#.phoneNumbers[*].type anyof ["iPhone"])].id
Note that this is definitely implementation-specific and will likely not work with any other library.

Related

Java converting nested JSON to CSV

I am creating a Java service that gets a JSON Object from a HTTP GET Request.
This is an example of the JSON Object I am getting:
{
"data": [{
"itemNumber": "547325645",
"manufacturer": "LV3",
"name": "Levis 501",
"minimumQuantity": "1.0",
"maximumQuantity": "10.0",
"prices": [{
"currency": "EUR",
"amount": "80.0"
}]
}, {
"itemNumber": "224145625",
"manufacturer": "LV3",
"name": "Levis 502",
"minimumQuantity": "1.0",
"maximumQuantity": "10.0",
"prices": [{
"currency": "EUR",
"amount": "90.0"
}]
}],
"pagination": {
"offset": 0,
"limit": 2,
"total": 1925
}
}
Right now I am using Jackson to map my HttpResponse into a JSON Object:
productListResponse = new BufferedReader (
new InputStreamReader(getResponse.getEntity().getContent(), StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
JsonNode productListJson = mapper.readTree(productListResponse);
The problem where I run into now is that I can't parse this JSON properly. For example, I want to omit many values, like the quantities or the currencies. I also want to convert the manufacturer value to another text, in this case "Levis". But what fails for now is the data list, this does not get along with the mapper. I get an empty object back, which does not contain the JSON, but I have already tested if I get a response at all and I do. The next problem would be, of course, that the prices are also in a list and there I also do not know how to go on.
Simply put, I just want a semicolon-separated CSV file where I pull individual values out of the JSON. Of course, I have already done a lot of research and also found reliable information, but it does not apply to my case.
These are some of the sources I have already used:
https://www.baeldung.com/java-converting-json-to-csv
Converting JSON to XLS/CSV in Java
https://docs.aspose.com/cells/java/convert-json-to-csv/

Sort the search result in ascending order of a multivalued field in Solr

I'm using Solr of version 6.6.0. I have a schema of title (text_general), description(text_general), id(integer). When I search for a keyword to list the results in ascending order of the title my code returns an error can not sort on multivalued field: title.
I have tried to set the sort using the following 3 methods
SolrQuery query = new SolrQuery();
1. query.setSort("title", SolrQuery.ORDER order);
2. query.addSort("title", SolrQuery.ORDER order);
3. SortClause ab = new SolrQuery.SortClause("title", SolrQuery.ORDER.asc);
query.addSort(ab);
but all of these returns the same error
I found a solution by referring to this answer
It says to use min/max functions.
query.setSort(field("pageTitle",min), ORDER.asc);
this what I'm trying to set as the query, I didn't understand what are the arguments used here.
This is the maven dependency that I'm using
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>6.5.1</version>
</dependency>
Unless title actually is multiValued - can your post have multiple titles - you should define it as multiValued="false" in your schema. However, there's a second issue - a field of the default type text_general isn't suited for sorting, as it'll generate multiple tokens, one for each word in the title. This is useful for searching, but will give weird and non-intuitive results when sorting.
So instead, define a title_sort field and use a field type with a KeywordTokenizer and LowerCaseFilter attached (if you want case insensitive sort), or if you want case sensitive sort, use the already defined string field type for the title_sort field.
The first thing to check is do you really need that title field to be multivalued, or do your documents really have multiple titles ? If not, you just need to fix the field definition by setting multivalued="false".
That said, sorting on a multivalued field doesn't make sense unless determining which one of these multiple values should be used to sort on, or how to combine them into one.
Let' say we need to sort a given resultset by title (alphabetically), first using a single-valued title field :
# Unsorted
"docs": [
{ "id": "1", "title": "One" },
{ "id": "2", "title": "Two" },
{ "id": "3", "title": "Three" },
]
# Sorted
"docs": [
{ "id": "1", "title": "One" },
{ "id": "3", "title": "Three" },
{ "id": "2", "title": "Two" },
]
# -> ok no problem here
Now applying the same logic with a multi-valued field is not possible as is, you would necessarily need to determine which title to use in each document to properly sort them :
# Unorted
"docs": [
{ "id": "1", "title": ["One", "z-One", "a-One"] },
{ "id": "2", "title": ["Two", "z-Two", "a-Two"] },
{ "id": "3", "title": ["Three", "z-Three", "a-Three"] }
]
Hopefully, Solr allows to sort results by the output of a function, meaning you can use any from Solr's function queries to "get" a single value per title field. The answer you referred to is a good example even though it may not work for you (because title would need docValues enabled - depends on field definition - and knowing that max/min functions should be used only with numeric values), just to get the idea :
# here the 2nd argument is a callback to max(), used precisely to get a single value from title
sort=field(title,max) asc

how to parse(separate structure and value) json format String in java

let's say I have a String which has a format as Json.
If I want to separate values from the String.
and exchange the values with '#number'.
Currently, I don't know the keys.
Is there any easy way to get this result?
for example,
from
{
"data": [
{
"skills": "Java",
"platforms": "Web"
}
],
"status": "100"
}
to
{
"data": [
{
"skills": #1,
"platforms": #2
}
],
"status": #3
}
with array result [Java, Web, 100]
Probably if you are looking to parse a unknown json and print the values Check this out
I wont be able to give you the exact code you need, but you should be able to implement on similar lines

Best practice for "connecting" json objects

My json:
{
"activities": [
{
"type": "post",
"id": "160",
"name": "John Wayne",
"content": "this is the actual post",
"timestamp" : "date + time",
},
{
"type": "post"
"id": "161",
"name": "Angelina Jolie",
"content": "this is the actual post",
"timestamp" : "date + time",
{
"type": "comment"
"id": "162",
"name": "Ravi Tamada",
"content": "content of the comment",
"timestamp" : "time + date",
"secondary_id": "160"
}
]
}
I have 2 types of objects which i have to consider: comment and post.
Every comment is linked to a post with its secondary id. That means if secondary_id is "160" this comment belongs to the the post with the id 160. In my json there could be 50 posts then 1 comment to the 2nd post follwed by 10 more psots and then 6 various comments. Means its not orderd.
So now im trying to figure out how to safe them in my java code to get them linked. Means i need every comment for a certain post. I could do 2 arrays 1 for posts 1 for comments and then search the comments array for every comment with the id 160...161..etc... this would be pretty messy i guess.
Isnt there some pattern or smth like the key is 160 and now give me all the secondary id´s mapped as value for that key or smth?
I hope you know what i mean, kinda of hard to expain.
Basically what i would need is smth like go through the json check if its post if yes safe it. If its a comment look up the secondary id and match it to the map(or smth) of the right primary id.
First of all when serializing JSON in java there are libraries you can use, Jackson for example.
Once you familiar yourself with Jackson, I would create a base class for comment and post that has all the fields that are shared by them.
I would create a custom deserializer that after creating a comment object looking up the post object and adding the comment to the post.

How to transplant an index into a solr core

My situation is this:
I have an index that has been generated by an entirely different app and I want to transplant/expose it from solr.
I can easily do that, but the problem now is I can't query on any of the fields. I just get empty {}
I modified the schema to include the fields from the documents transplanted and it doesn't seem to have made a difference.
When I do a q=*:* I can see all the documents so I know the info is there. This has to be easy. I am just missing it.
Would anyone like to give me an education?
Document example:
"docs": [
{
"code": "A000",
"description": "Cholera due to Vibrio cholerae 01, biovar cholerae",
"version": "10",
"concepts": [
"cholera",
"cholera-due to biovar cholera",
"cholera-due to vibrio cholerae 01",
"infectious diseases",
"intestinal infectious diseases"
],
"tags": [
"biovar",
"cholera",
"cholerae",
"diseases",
"infectious",
"intestinal",
"vibrio"
],
"category": "A00",
"etiology": "0"
},
]

Categories

Resources