How can i dynamically Create Criteria Mongodb Spring data mongo Template - spring

I need to dynamically create a criteria but i am having problem how can i build criteria dynamically.
I need exactly the same as in here Build dynamic queries with Spring Data MongoDB Criteria but i am getting an error while i am converting my Criteria list to a toArray as its keep saying that orCriteria does not have support for Criteria[]
here is my effort so far
Here is my query structure
{
"query":{
"where":[{
"or":[
{
"fieldName":"title","fieldValue":"Demo Event NEW YORK IIII22222",
"operator":"equal"
},
{
"fieldName":"createdBy","fieldValue":"system",
"operator":"equal"
}
]
}
]
}
}
and here is my parsing it to create criteria
if(null != eventSearch.getQuery())
{
if(null != eventSearch.getQuery().getWhere() && eventSearch.getQuery().getWhere().size()> 0)
{
for (Where whereClause : eventSearch.getQuery().getWhere()) {
if(null != whereClause.getOr() && whereClause.getOr().size() > 0){
for (Field field: whereClause.getOr()) {
if(field.getOperator().equalsIgnoreCase(QueryOperator.IS))
{
// So i need to append an or Condition to main query for each or object in my query can anyone tell me how can i achieve this?
query.addCriteria(Criteria.where(whereClause.getFieldName()).gte(whereClause.getFieldValue()));
}
}
}
}
}
I need to pass my all where clauses with in or object to orOperator function as a parameter
Criteria c = new Criteria().orOperator(Need to pass my where clauses here);

Better use an ArrayList of Criteria to keep $or criteria as below.
List<Criteria> orCriteriaList = new ArrayList<Criteria>();
for (Field field: whereClause.getOr()) {
if(field.getOperator().equalsIgnoreCase(QueryOperator.IS)){
Criteria c1 = Criteria.where(whereClause.getFieldName()).gte(whereClause.getFieldValue());
orCriteriaList.add(c1);
}
}
Then build the main query from this orCriteriaList as
mainQuery.addCriteria(new Criteria().orOperator(orCriteriaList.toArray(new Criteria[orCriteriaList.size()])));

Related

spring boot + hibernate Can I use entityMnager.persist(item) after I get the item with named query?

I am using spring boot and hibernate. I have a named query where I select an item. Then I want to set some property and then to make entityManager.persist() or entityManager.merge(). Can I do this or the instance of my item will be unmanaged after the named query and persist/merge will fail ?
Here is my code where em.persist() actually do not work:
public String getSMSText(String sourceUrl) {
Rss rss;
List urls = em.createNamedQuery("Rss.getFeedByUrl").setParameter("url", sourceUrl).getResultList();
if (urls.size() != 0) {
rss = (Rss) urls.get(urls.size() - 1);
for (Rss.Item item : rss.getChannel().getItems()) {
try {
if (Utils.isToday(item.getPubDateAsDate()) && !item.isPushed()) {
item.setPushed(true);
em.refresh(item);
em.persist(item);
return item.getTitle() + "." + item.getSummary();
}
} catch (ParseException e) {
logger.info("Cannot parse pub date", e);
}
}
logger.info(sourceUrl + " No news for today!");
return null;
}
return null;
}
My guess is that your change on the item will not have any effect.
You should change your item only when the query transaction is completely closed.
I think you have two way:
1- Change your code to update your entity only when you are sure that the select query transaction was closed.
2- Use EntityManager.refresh() on your item, after the named query and before change and persist it.

How can I do a WpGraphQL query with a where clause?

This works fine
query QryTopics {
topics {
nodes {
name
topicId
count
}
}
}
But I want a filtered result. I'm new to graphql but I see a param on this collection called 'where', after 'first', 'last', 'after' etc... How can I use that? Its type is 'RootTopicsTermArgs' which is likely something autogenerated from my schema. It has fields, one of which is 'childless' of Boolean. What I'm trying to do, is return only topics (a custom taxonomy in Wordpress) which have posts tagged with them. Basically it prevents me from doing this on the client.
data.data.topics.nodes.filter(n => n.count !== null)
Can anyone direct me to a good example of using where args with a collection? I have tried every permutation of syntax I could think of. Inlcuding
topics(where:childless:true)
topics(where: childless: 'true')
topics(where: new RootTopicsTermArgs())
etc...
Obviously those are all wrong.
If a custom taxonomy, such as Topics, is registered to "show_in_graphql" and is part of your Schema you can query using arguments like so:
query Topics {
topics(where: {childless: true}) {
edges {
node {
id
name
}
}
}
}
Additionally, you could use a static query combined with variables, like so:
query Topics($where:RootTopicsTermArgs!) {
topics(where:$where) {
edges {
node {
id
name
}
}
}
}
$variables = {
"where": {
"childless": true
}
};
One thing I would recommend is using a GraphiQL IDE, such as https://github.com/skevy/graphiql-app, which will help with validating your queries by providing hints as you type, and visual indicators of invalid queries.
You can see an example of using arguments to query terms here: https://playground.wpgraphql.com/#/connections-and-arguments

How to query relational data using subclasses? parse.com and Unity

Im trying to query all elements of subclass in Unity. I have found SDK constraint or missing something here.
According to documentation querying subclasses is possible.
> var query = new ParseQuery<Armor>()
.WhereLessThanOrEqualTo("rupees", ((Player)ParseUser.CurrentUser).Rupees);
query.FindAsync().ContinueWith(t =>
{
IEnumerable<Armor> result = t.Result;
});
Im however using relation table and cannot specify
Here is my code:
IEnumerator LoadMyDesigns(Action<RequestResult> result) {
ParseUser user = ParseUser.CurrentUser;
ParseRelation<Design> relation = user.GetRelation<Design>("designs");
Task<IEnumerable<Design>> task = relation.Query.FindAsync();
while (!task.IsCompleted) yield return new WaitForEndOfFrame();
if (task.IsFaulted) {
//error
foreach(var e in task.Exception.InnerExceptions) {
ParseException parseException = (ParseException) e;
Debug.LogError("Error message " + parseException.Message);
Debug.LogError("Error code: " + parseException.Code);
result(new RequestResult(true, parseException.Message));
}
}
else {
result(new RequestResult(true, new List<Design>(task.Result)));
}
}
And error:
ArgumentNullException: Must specify a ParseObject class name when creating a ParseQuery.
So the question is how do I specify query subclass type when using relations?
Thanks.
I've struggled with the same problem and in my case I needed to provide the propertyName again in de GetRelationProperty call.
For example:
[ParseFieldName("designs")]
public ParseRelation<Design> Designs
{
get { return GetRelationProperty<Design>("Designs"); }
}
Try querying your designs Table.
Make a new query for class "Designs" where equal("owner", PFUser.currentUser())
This should return all of the designs for the current User.

optimizing search query with criteria combination

i have a list of search inputs ( 4 search inputs ) , as criteria i have to do a combination to get a list of books ( by author , by publish date , by name , by number of pages )
this is the code
if((author!="") && (date!="")&&(name!="")&&(numPages!="")){
//query getting the books with th 4 criteria
}else{ if((author!="") &&(name!="")&&(numPages!="") ){
//query getting the books with th 3 criteria
}
} etc
is there a better way to do the combination of those criteria
EDIT
this is one of the queries with criteria :
def invoiceListbyAll=Invoice.createCriteria().list {
eq("author", authorObj)
eq("name", name)
eq("numPages", numPages)
}
You could write it as:
def invoiceListbyAll=Invoice.createCriteria().list {
// from your code I assume that all parameter are strings
if (author) { // groovy empty strings act as boolean false
eq("author", authorObj)
}
if (name) {
eq("name", name)
}
if (numPages) {
eq("numPages", numPages)
}
}

unable to apply sort order in solr

hi Please tell me how to apply multiple valued sort order in solr here is my code given below,
I am using solr net for this.
private QueryOptions ConstructQueryOperation(SearchCriteria searchCriteria)
{
QueryOptions queryOption =new QueryOptions();
queryOption.Rows = searchCriteria.Pagination.PageSize;
queryOption.Start = ((searchCriteria.Pagination.CurrentPage+1) - 1) * searchCriteria.Pagination.PageSize;
if (searchCriteria.SortCriteria != null)
{
foreach (var sortItem in searchCriteria.SortCriteria)
{
if (sortItem.Value.ToString() == ListSorter.SortingOrder.Descending.ToString())
{
queryOption.AddOrder(new SolrNet.SortOrder(sortItem.Key, Order.DESC));
}
else
{
queryOption.AddOrder(new SolrNet.SortOrder(sortItem.Key, Order.ASC));
}
}
}
return queryOption;
}
I am getting a bad server request.
Can anyone let me know what needs to be done exactly.
It was a field name mismatch. .Net code was referring to a field that didn't exist in the Solr schema.

Resources