I'm switching from lucene to solr and I'm querying it with solrj.
After a query I'd like to obtain the explain and I executed this code:
QueryResponse queryResult = solrClient.query(collection, query, POST);
List<SolrDocument> recommended = queryResult.getResults();
Map<String, String> explainMap = queryResult.getExplainMap();
Map<String, Object> debugMap = queryResult.getDebugMap();
The explainMap contains the explanation of my query as a String.
Is it possible to obtain an object of explanation to avoid parsing the string?
For example I'd like to extract all the fields that matched and their value (without score and its composition).
My documents have only one textual field and many categorical or numeric fields.
Related
I need to copy the records of one table to another table based on some condition.
String query = "insert into public.ticket_booking_archive select * from public.ticket_booking where ticketId in (:ticketIds)";
So here the :ticketIds are dynamic, where i need to pass ticketIds to make sure whether it satisfies the condition. So it may be the matching and non matching ticket id's here at runtime.
The values of ticketIds are something like this
('f1fa3a42-5837-11ec-bf63-0242ac130002','516fd14d-3c9d-4b4b-91a0-b684d8592dfe','c9652f86-734c-4df5-8ef9-d407cb3eaf7a','df7f2812-b445-45b4-b731-da23c36d7738','f1fa3a42-5837-11ec-bf63-0242ac130002'). And this is just an example. And the list might goes on.
Since it is of type UUID, I'm storing it into a Set<UUID>
Set<UUID> tktIds = new HashSet<UUID>();
for(int i=0 ; i<ticketIds.size(); i++) {
String ticketId = ticketIds[i];
tktIds.add(UUID.fromString(ticketId));
}
Map<String, Object> params = new HashMap<>();
params.put("ticketIds", tktIds);
SqlParameterSource namedParameters =
new MapSqlParameterSource().addValue("ticketIds",params.get("ticketIds"));
Since I'm using NamedParameterJdbcTemplate, so I'm using like below
int res = writeNamedJdbcTemplate.update(query, namedParameters);
res = 3 when executed programmatically.
Here the problem is, as soon as it finds the first matching value in the IN clause it executes. And it is not considering the other matching values (ticketIds here)
But if I execute the same query in pgadmin it works fine
insert into public.ticket_booking_archive select * from public.ticket_booking where ticketId in ('f1fa3a42-5837-11ec-bf63-0242ac130002','516fd14d-3c9d-4b4b-91a0-b684d8592dfe','c9652f86-734c-4df5-8ef9-d407cb3eaf7a','df7f2812-b445-45b4-b731-da23c36d7738','f1fa3a42-5837-11ec-bf63-0242ac130002');
result is 6. Working as expected.
writeNamedJdbcTemplate.queryForObject(query, namedParameters, Integer.class); //. throws an error
Can anyone please assist? I'm really not sure where I'm making a mistake
I am not quite sure whether you are using the appropriate JDBC template for the named parameters, but you can do the following:
you can consult this article to use the right template and employ proper SQL query composition,
for string passing you can wrap the parameter mapping as shown here
after all your named parameter should work
I have imported data from a CSV file into Flink Java. One of the attributes I had to import as string (attribute Result) because of parsing errors. Now I want to convert the String to a Double. But I dont know how to do this with a object of the TableSource, Table or DataSet class. See my code below for this.
I've looked into flink documentation and tried some solutions with Map and FlatMap classes. But I did not find the solution for this.
BatchTableEnvironment tableEnv = BatchTableEnvironment.create(fbEnv);
//Get H data from CSV file.
TableSource csvSource = CsvTableSource.builder()
.path("Path")
.fieldDelimiter(";")
.field("ID", Types.INT())
.field("result", Types.STRING())
.field("unixDateTime", Types.LONG())
.build();
// register the TableSource
tableEnv.registerTableSource("HTable", csvSource);
Table HTable = tableEnv.scan("HTable");
DataSet<Row> result = tableEnv.toDataSet(HTable, Row.class);
I think it should work to use a combination of replace and cast to convert the strings to doubles, as in "SELECT id, CAST(REPLACE(result, ',', '.') AS DOUBLE) AS result, ..." or the equivalent using the table API.
In Java, using the Jackson ObjectMapper, I'm trying to deserialize a dynamo db object being read from a dynamo db stream.
I first call:
record.getDynamodb().getNewImage().get("primaryKey").getS().toString()
to get the primaryKey value of "1_12345" back from the stream.
I then use it in the object mapper to create a new instance of the Metrics object with the primaryKey member set:objectMapper.readValue("1_12345", Metrics.class);
The problem is I get an exception on that call:
Unexpected character ('_' (code 95)): Expected space separating root-level values
Metrics.class is a simple POJO with no constructor. I'm wondering if I need any special annotations or escape characters in my readValue call. I can't seem to find any clear indications on what the solution is in the case of this error.
(Side note - the reason I can't parse it straight from the json is because the json's structure when it's parsed from the stream isn't straightforward, a value looks like this, S indicating String, N for number etc:
{primaryKey={S: 1_12345,}, rangeKey={N: xxx}... etc. })
Thank you, that was the problem, the readValue() call takes a String in the format of JSON. The solution was to convert the dynamo streamed image into lists & maps (using the dynamodbv2 libs) until it was in the correct format as below:
Map<String, AttributeValue> newImage = record.getDynamodb().getNewImage();
List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>();
listOfMaps.add(newImage);
List<Item> itemList = InternalUtils.toItemList(listOfMaps);
for (Item item : itemList) {
String json = item.toJSON();
Metrics metric = objectMapper.readValue(json, Metrics.class);
}
In HttpServletRequest, getParameterMap returns a Map of all query string parameters and post data parameters.
Is there a way to get a Map of ONLY query string parameters? I'm trying to avoid using getQueryString and parsing out the values.
You can use request.getQueryString(),if the query string is like
username=james&password=pwd
To get name you can do this
request.getParameter("username");
Contrary to what cularis said there can be both in the parameter map.
The best way I see is to proxy the parameterMap and for each parameter retrieval check if queryString contains "&?<parameterName>=".
Note that parameterName needs to be URL encoded before this check can be made, as Qerub pointed out.
That saves you the parsing and still gives you only URL parameters.
The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.
The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":
GET /persons?age=42
The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":
PUT /persons?age=42
hair=grey
So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2 will return
password : [pwd1, pwd2] (length = 2)
username : [james, smith] (length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
Java 8
return Collections.list(httpServletRequest.getParameterNames())
.stream()
.collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));
I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending
http://mycompany.com/myapp/myservlet?first=11&second=22
say:
http://mycompany.com/myapp/myservlet/11/22
I have one column in my table which will store data in string format the sample data is
{"pre-date":{"enable":true,"days":"3","interval":"1","mail-template":"582"},"on-date":{"enabled":false},"post-date":{"enabled":false}}
and the string contains data like json data
but when i will send this record for controller to view it should be in format
enable : true
days : 3
interval : 1
so that i can set values to respective form elements how to do this in java any help
Read the complete JSON string from the database, then parse it using a JSON parser, and extract the information you're interested into from the data structure/object returned from the parsing.
There are lots of JSON parsers available. Look at this page, which lists a number of them in the Java section (you have to scroll a little bit down).
Jackson provides the best support for simple conversion of any JSON object into a Java Map comprised of only Java SE components.
Following is an example using the JSON from the original question.
// {"pre-date":{"enable":true,"days":"3","interval":"1","mail-template":"582"},"on-date":{"enabled":false},"post-date":{"enabled":false}}
String json = "{\"pre-date\":{\"enable\":true,\"days\":\"3\",\"interval\":\"1\",\"mail-template\":\"582\"},\"on-date\":{\"enabled\":false},\"post-date\":{\"enabled\":false}}";
ObjectMapper mapper = new ObjectMapper();
// To put all of the JSON in a Map<String, Object>
Map<String, Object> map = mapper.readValue(json, Map.class);
// Accessing the three target data elements
Map<String, Object> preDateMap = (Map) map.get("pre-date");
System.out.println(preDateMap.get("enable"));
System.out.println(preDateMap.get("days"));
System.out.println(preDateMap.get("interval"));