When filtering with DSL if the filters that are being passed are empty then the results are empty. Could you please give some suggestions on how to ignore URL parameters that are not set.
Example:
#Query(value ="{$and:[{'country.name':{$eq:?0}},{'providerName':{$eq:?1}}]})"
The above query is working fine and the documents are returned. But if the positional filters are null then the result is empty. How to write a query that ignores the parameters if the value is not set.
Kind Regards,
Ajay
In this case I would highly recommend to use Query API to build the query based on the parameter is being passed, but if you want to use query DSL, it can be done something like this, you have to check for null and can build the query accordingly.
#Query("{$and :["
+ "?#{ [0] == null ? { $where : 'true'} : { 'country.name' : {$eq:[0]}} },"
+ "?#{ [1] == null ? { $where : 'true'} : { 'providerName' : {$eq:[1]}}}"
+ "]}")
Reference: mongodb.repositories.queries.json-spel
Related
How can I write not equal in where in laravel query builder ?
I would like to query like this
e.g.
select * from Table where a != '1' and a != '2' and a != '4' and a != '6' ;
$removeIdListArray = (1,2,4,6);
$removedIdList = Stack::
->where('columnA',$removeIdListArray);
//↑What should I do?
You can use whereNotIn and pass an array as the second parameter
$removeIdListArray = [1,2,4,6];
$removedIdList = Stack::whereNotIn('columnA', $removeIdListArray);
Reference: Database: Query Builder
The most fluent way :
Model::query()->whereNotIn('column', $arrayOfValues);
I will recommend you always using query() method together with your models, since it will allow you to explore all of the available options for the Laravel Model class
Simply :
->where('columnA', '!=', $removeIdListArray);
or
->whereNot('columnA', $removeIdListArray);
I am trying to pass a null parameter (:searchQuery) to a native query in Spring Boot, I have tried various different ways but whenever I pass null I get the error
ERROR: operator does not exist: text ~~ bytea
Query
#Query(value = "SELECT count(*) FROM analysis_history ah, analysis_group ag WHERE ah.analysis_group_id = ag.id "
+ "AND ah.creation_date BETWEEN :from AND :to AND ((:searchQuery IS NULL) OR (:searchQuery IS NOT NULL AND ag.name LIKE :searchQuery))", nativeQuery = true)
Long count(#Param("from") Date from, #Param("to") Date to, #Param("searchQuery") String searchQuery);
Can anyone help?
You cannot use like null
SELECT count(*) FROM analysis_history ah, analysis_group ag
WHERE ah.analysis_group_id = ag.id AND ah.creation_date
BETWEEN :from AND :to AND ag.name LIKE :searchQuery
And you pass '%' in the searchQuery when the searchQuery parameter is null? e.g.
repository.count(from, to, searchQuery == null ? "%" : searchQuery);
There is a way to bypass this, but you need access to the EntityManager, and not use the #Query annotation to create that implementation for you.
Long count(Date from,Date to, String searchQuery) {
Number n = em.createNativeQuery("... that query")
.setParameter("from", from, TemporalType.DATE) // assuming that's a Date, and not TimeStamp
.setParameter("to", to, TemporalType.DATE)
.setParameter("searchQuery", "")
.setParameter("searchQuery", searchQuery)
.getSingleResult();
return n.longValue();
}
The first call to .setParameter("searchQuery", "") tells Hibernate what type this is, the next one sets the value.
The problem comes from Postgres doing the typecheck during parsing, and not deferring the error in case the parameter set is a null.
An alternative workaround to the issue posed by #coladict, which is compatible with Query and performs as well as the original would.
SELECT count(*)
FROM analysis_history ah, analysis_group ag
WHERE ah.analysis_group_id = ag.id
AND ah.creation_date BETWEEN :from AND :to
AND (:searchQuery IS NULL OR ag.name LIKE CAST(:searchQuery AS CHARACTER VARYING))
I'm using the jdbc input plugin to get data from "table1":
statement => "SELECT * FROM table1 where id=1"
Result is : id:1 and id_subscriber:1
Then I'm using the jdbc_streaming filter plugin to get more data from "table2" using the "id_subscriber" field value from the previous statement, so I'm using the following statement which gets me an empty result :
statement => "SELECT * FROM table2 where id_subscriber = :idsub"
parameters => { "idsub" => "%{id_subscriber}"}
target => "arrayOfResults" #arrayOfResults is an empty array
If I use the id_subscribe value directly in the following statement, I get the four records I'm looking for :
statement => "SELECT * FROM table2 where id_subscriber = 1"
target => "arrayOfResults" # I get the right result
Can you tell me what Im I doing wrong ?
Thank you.
My bad, I did not understand how the "parameters" option works.
The right answer if someone came across this issue is simply :
`parameters => { "idsub" => "id_subscriber"}`
The right sided part of parameters was referring to the field name and not it's value.
I want to query a datatable (dt) and load a 2nd dt with the resultant collection of datarows. Fine - we have the CopyToDataTable() extn mthd for exactly that purpose. However it is constrained to enumerate only over DataRows, which means that I cannot return anything else e.g. a collection of anonymous types. So - how can I modify the values in the datarows?
Eg I have a dt with 3 columns: MyPK, VARCHAR01, VARCHAR02.
Foreach row, if VARCHAR01 or VARCHAR02 has the value "" (i.e. String.Empty) I want to replace that with NULL (which the underlying type allows).
I would do this as follows:
var MyCleanedDatarows =
from o in ds.Tables["dt"].AsEnumerable()
select new {
MyPK = o.Field<string>("MyPK"),
VARCHAR01 = (o.Field<string?>("VARCHAR01") == "" ? NULL : o.Field<string?>("VARCHAR01") ),
VARCHAR02 = (o.Field<string?>("VARCHAR02") == "" ? NULL : o.Field<string?>("VARCHAR02") )
};
...but then I cant use CopyToDataTable() to get back to a dt. I'm thinking I need to modify the datarows before invoking select operator, but I dont know how to achieve that. Any help/thoughts would be v.greatfully recieved.
Thanks in advance,
Tamim.
Take a look at this approach, in MSDN documentation.
http://msdn.microsoft.com/en-us/library/bb669096.aspx
Get value out of DateTime column
if null to return String.Empty
else
DateTime.ToShortDateString
What am I doing wrong => query produced below:
var queryable = from p in Products
select new {
selldate = p.SellEndDate == null
? string.Empty
: p.SellEndDate.Value.ToShortDateString() };
Error: InvalidOperationException: Could not translate expression 'Table(Product).Select(p => new <>f__AnonymousType01(selldate = IIF((p.SellEndDate = null), Invoke(value(System.Func1[System.String])), p.SellEndDate.Value.ToShortDateString())))' into SQL and could not treat it as a local expression.
Basically what's happening here is that LINQ to SQL is taking your entire query and trying to convert it into something that SQL Server can understand. The problem, though, is that SQL Server has no concept of DateTime.ToShortDateString, so the conversion to SQL fails.
You'll have to change your query so that it just selects SellEndDate (which will get it as a Nullable<DateTime>) and then when you use the results of that query you can do the conversion to string. For example:
var list = (from p in Products
select p.SellEndDate).ToList();
// calling ToList() above means we have the entire resultset in memory and
// no longer have to pass the query back to SQL Server
var stuff = from p in list select new
{
selldate = p.SellEndDate == null ?
string.Empty :
p.SellEndDate.Value.ToShortDateString()
};
ToShortDateString doesn't seem to have equivalent SQL translation.
Use ToString instead.
If the date time field allows nulls:
from order in repository.Order
select order.OrdShipDate == null ? "" : order.OrdShipDate.GetValueOrDefault(DateTime.Now).Month.ToString() + "/" + order.OrdShipDate.GetValueOrDefault(DateTime.Now).Day.ToString() + "/" + order.OrdShipDate.GetValueOrDefault(DateTime.Now).Year.ToString();
If the date time field doesn't allow nulls:
from order in repository.Order
select order.OrdShipDate.Month.ToString() + "/" + order.OrdShipDate.Day.ToString() + "/" + order.OrdShipDate.Year.ToString();