Spring data elastic search date issue when search - spring-boot

I am using spring-boot-starter-parent 2.5.4 and elasticsearch 7.12.1 and basically am able to insert a document with createDate as field successfully but unable to search.
I have a Spring rest webservice that contains search functionality that search by range of date and contains the request in json below:
{
"dateTo": "20210901T152702.620+04:00",
"dateFrom": "20200901T152702.620+04:00"
However when execute the search of createdDate the following error is displayed :
021-09-01 15:45:18.149 WARN 19588 --- [nio-9088-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.ZonedDateTime` from String "20210901T152702.620+04:00": Failed to deserialize java.time.ZonedDateTime: (java.time.format.DateTimeParseException) Text '20210901T152702.620+04:00' could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.ZonedDateTime` from String "20210901T152702.620+04:00": Failed to deserialize java.time.ZonedDateTime: (java.time.format.DateTimeParseException) Text '20210901T152702.620+04:00' could not be parsed at index 0e
Please find below my document:
public class Logging {
#Id
private String id;
#Field(type = FieldType.Text, name = "username")
private String username;
#Field(type = FieldType.Date, format = DateFormat.basic_date_time)
private ZonedDateTime createdDate = ZonedDateTime.now();
}
My request is shown below:
public class LoggingSearchCriteria extends AbstractSearchRequest {
private ZonedDateTime dateTo;
private ZonedDateTime dateFrom;
}
Any idea why I am getting this error when executing the search command?
Thnks in advance

Related

Failed parsing for a LocalDate value while using Spring Data Rest

I am still a newbie with Spring Data Rest and I'm having some issues with it while I have to parse a LocalDate value to an endpoint. I have searched info's in other topics too but I'm still stucked, this is the problem:
I have one Entity with this code .
#Entity
#Table(name="calendario_parcheggio")
#Setter
#Getter
public class CalendarioParcheggio {
#Id
#Column(name="data_parcheggio")
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE )
#JsonFormat(pattern="yyyy-MM-dd")
private LocalDate data;
#Column(columnDefinition = "ENUM('ATTIVO', 'ARCHIVIATO')")
#Enumerated(EnumType.STRING)
private Stato stato;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="data_parcheggio")
private List<Parcheggio> parcheggio;
public enum Stato {
ATTIVO,
ARCHIVIATO,
}
}
It's an Entity linking the Date and its status for a Parking that works hourly.Matching this table on MySQL
CREATE TABLE calendario_parcheggio (
data_parcheggio DATE PRIMARY KEY,
stato ENUM ('ATTIVO','ARCHIVIATO') NOT NULL DEFAULT ('ATTIVO')
);
When I start the server everything is ok , but when i try (by browser or Postman) to check the data of a particular instance (in my case : "http://localhost:8080/parkingsystem/api/calendario-parcheggio/2022-10-18") ,I get this problem :
{"cause":
{"cause":
{"cause": null,
"message": "Text '2022-10-18' could not be parsed at index 2"
},
"message": "Parse attempt failed for value [2022-10-18]"
},
"message": "Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '2022-10-18';
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-10-18]"
}
And this is the Repository
#RepositoryRestResource(collectionResourceRel="calendarioParcheggio", path="calendario-parcheggio")
public interface CalendarioParcheggioRepository extends JpaRepository<CalendarioParcheggio, LocalDate> {
}
Can you help me to find the solution please?I hope I have explained the problem well enough, my English is still in training :)

How to save elasticsearch date type in spring data?

I want to use spring data to get elasticsearch documents, but encountered some problems with get data.
Here is my code.
Entity:
#Id
private String id;
#Field(name = "#timestamp", type = FieldType.Date)
private Date timestamp;
#Field(name = "netflow.first_switched", type = FieldType.Date)
private Date firstSwitched;
#Field(name = "netflow.last_switched", type = FieldType.Date)
private Date lastSwitched;
My data in elasticsearch:
I want to test spring data can get document or not(implement ElasticsearchRepository), so I hard code ID like:
Optional<OriginalData> a = originalDataService.findById("nfQ8KHMBB49SfiIiH2rK");
And then I got an exception:
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2020-07-07T07:44:54.878Z'; nested exception is java.lang.IllegalArgumentException
so I modify my Entity code to
#Id
private String id;
// #Field(name = "#timestamp", type = FieldType.Date)
// private Date timestamp;
#Field(name = "netflow.first_switched", type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private LocalDateTime firstSwitched;
#Field(name = "netflow.last_switched", type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private LocalDateTime lastSwitched;
still wrong, but got another exception:
org.springframework.data.elasticsearch.core.convert.ConversionException: could not create object of class java.time.LocalDateTime
My questions are:
How to use spring data get elasticsearch document with field containing data type?
I want to get field "#timestamp", can I get this?
Does anyone can help me, please?
Kase

Solr undefined field active

I am getting this undefined field 'active' error, but active field exist in schema. This was working previously without any errors, suddenly this error appears:
My Solr Document:
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class SDocument {
#Id
#Field
private String indexId;
#Field("code")
private String code;
#Field("name")
private String name;
#Field("active")
private Boolean active;
}
I'm using spring boot with solrCrudRepository and query was
#Query(value = "code:?0* name:?0*", filters = "active:?1")
List<SDocument> findAllergenList(String searchKey, Boolean isActive);
org.springframework.data.solr.UncategorizedSolrException: undefined field active; nested exception is org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: undefined field active
at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:136)
at org.springframework.data.solr.core.SolrTemplate.count(SolrTemplate.java:154)
at org.springframework.data.solr.repository.query.AbstractSolrQuery$CollectionExecution.count(AbstractSolrQuery.java:435)
at org.springframework.data.solr.repository.query.AbstractSolrQuery$CollectionExecution.execute(AbstractSolrQuery.java:415)
at org.springframework.data.solr.repository.query.AbstractSolrQuery.execute(AbstractSolrQuery.java:149)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:415)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:393)

Spring Data query over two documents

I have an m:n connection in my MongoDB, MessageUserConnection is the class between User and Message.
Now I will get all MessageUserConnections where MessageUserConnection#confirmationNeeded is true, read is false and Message#receiveDate is not older than the last week.
Is there any possibility to do this with Spring Data?
Thanks a lot!
public class MessageUserConnection {
#Id
private String id;
#DBRef
private User userCreatedMessage;
#DBRef
private Message message;
private Boolean confirmationNeeded;
private Boolean read;
}
public class Message {
#Id
private String id;
private String title;
private String message;
private DateTime receiveDate;
}
[EDIT]
I have tried it by my own:
#Query("FROM MessageUserConnection AS muc WHERE muc.confirmationNeeded = ?0 AND muc.message.receiveDate = ?1")
List<MessageUserConnection> findMessageUserConnectionByConfirmationNeededAndReceiveDate(final Boolean confirmationNeeded, final DateTime receiveDate);
and I get the following exception:
Caused by: com.mongodb.util.JSONParseException:
FROM MessageUserConnection AS muc WHERE muc.confirmationNeeded = "_param_0" AND muc.message.receiveDate = "_param_1"
Does anyone know what I am doing wrong here?
Thanks a lot!
[EDIT]
I run into another problem. My query currently looks like this.
#Query("{$and : [{'confirmationNeeded' : ?0}, {'message.receiveDate' : ?1}]}")
where confirmationNeeded is a boolean and message.receiveDate is Joda#DateTime. With this query I get the following exception:
org.springframework.data.mapping.model.MappingException: Invalid path reference message.receiveDate! Associations can only be pointed to directly or via their id property!
Does that mean that I only can join to message.id?
Thanks a lot!

Gson Custom deserializer

I want to deserialize json string to java object. My class structure is this
public class Category {
String name;
int id;
ArrayList<Catalog> catalogs;
}
and catalog class structure is this
public class catalog {
private int catalogId = 0;
private String catalogName;
}
Following code i used to deserialize
Gson gson = new Gson();
ArrayList<Category> categories = gson.fromJson(jsonString, Category.class);
I got exception when it try to deserialize ArrayList catalogs;
If i remove ArrayList then it parse successfully
Thanks
Pawan
I solved this problem. The problem is that the string which i am parsing contain boolean value instead of Array . So There is exception while parsing.
The reason is that datatype is not match in json string which is parsed.
Thanks

Resources