optimizing search query with criteria combination - algorithm

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)
}
}

Related

Graphql Filter by query

So I'm trying to learn graphql I've been playing around with the ENS subgraph on the graph
I've figured out how to do simple filtering but when I try to write more complex filters they do not compile.
I'm trying to get the top 5 transactions for the each of the top 5 domains. (e.g for each domain I want the top 5 transactions)
{
#Sample Query to get the first 5 domains (not needed for question but used to validate results)
domains(first: 5) {
id
name
labelName
labelhash
}
#attempt to filter the transfer.domain.id by TOP 5 domains.id
transfers(where: { domain { id: domains(first: 5) { id } } }) {
id
domain {
id
}
blockNumber
transactionID
}
}
EDIT I'm going to attempt to simplify my request since I'm not sure nesting queries is possible. How can I filter an inner query by Id:
transfers(where: {domain.id: "0x9c0fc2519ae862cee27778e5c34714d6c7e3ca21ad572df47ad9f6fe530909bd"}) {
id
domain {
id
}
blockNumber
transactionID
}
NOTE: Domain.Id = does not compile how would I write a filtered query like that?
However, My filter doesn't compile syntactically. How can I write a query which filters by a child property?
You can query like this
query {
getPost(id: "0x1") {
title
text
datePublished
}
}
Got this from https://dgraph.io/docs/graphql/queries/search-filtering/

How to check record is fully empty on left join in jooq query

I try to fetch a record from table with left join on another table. An information in the second table can be not found but I expect an information from the first table.
val citizenship = Tables.COUNTRIES.`as`("citizenship")
try {
return context.selectFrom(Tables.CLIENT_PROJECTIONS
.leftJoin(citizenship).on(
Tables.CLIENT_PROJECTIONS.CITIZENSHIP_COUNTRY_CODE.eq(
citizenship.CODE_ALPHA2
)
)
).where(Tables.CLIENT_PROJECTIONS.ID.eq(id)).fetchOne {
val clientProjection = ClientProjectionMapper.map(it.into(Tables.CLIENT_PROJECTIONS)) ?: return#fetchOne null
clientProjection.citizenship = CountryMapper.map(it.into(citizenship))
clientProjection
}
} catch (ex: DataAccessException) {
logger.error("Failed to access to database", ex)
throw ex
}
I convert data from CountriesRecord to Entity in CountryMapper:
object CountryMapper : RecordMapper<CountriesRecord, Country> {
override fun map(record: CountriesRecord?): Country? = when {
record != null -> {
Country(
countryCode = record.codeAlpha,
title = record.title
)
}
else -> {
null
}
}
}
But if query returns null in every fields of CountriesRecord my map method receive a non-nullable entity but everyone fields of this entity is empty.
I can check every field of CountriesRecord is it null but i think that isn't good idea. Can I check it by another more best way? May be I should write more correct query to database?
A LEFT JOIN in SQL does exactly that. It produces nulls for all columns of the left joined table for which there was no match in the join's ON clause.
You don't have to check whether each column is null. The primary key will be good enough, because that should have a NOT NULL constraint on it, meaning that if the primary key value is null (record.codeAlpha), then that must be because of the LEFT JOIN.
Change your second mapper to this:
object CountryMapper : RecordMapper<CountriesRecord, Country> {
override fun map(record: CountriesRecord?): Country? = when {
record?.codeAlpha != null -> {
Country(
countryCode = record.codeAlpha,
title = record.title
)
}
else -> {
null
}
}
}

How can i dynamically Create Criteria Mongodb Spring data mongo Template

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()])));

Magento - Get Country Id from Name - is there a easier/quicker way?

I need to load the 2 letter ISO2 country ID for a given country name.
Right now, I use the following method to do this:
// Method to Get countryId from CountryName
function getCountryId($countryName) {
$countryId = '';
$countryCollection = Mage::getModel('directory/country')->getCollection();
foreach ($countryCollection as $country) {
if ($countryName == $country->getName()) {
$countryId = $country->getCountryId();
break;
}
}
$countryCollection = null;
return $countryId;
}
Usage:
var_dump(getCountryId('Germany'));
Outputs:
string(2) "DE"
Is there a easier/quicker way to do this instead of loading the country collection and iterating through it every time?
Surprisingly, looping is the only way you'll achieve this.
The country names are stored in XML files in lib/Zend/Locale/Data/ and they're organized by locale (en, es, fr) and then country code, not country name.
Since it's not a SQL table you can't add a WHERE clause (using Magento's addFieldToFilter()), so you'll be looping through the XML nodes anyway.
There is no other way, because of translations. This is function for getting country name, you can't reverse it
public function getName()
{
if(!$this->getData('name')) {
$this->setData(
'name',
Mage::app()->getLocale()->getCountryTranslation($this->getId())
);
}
return $this->getData('name');
}

How do I sort by a property on a nullable association in Grails?

I'm trying to sort a table of data. I have the following domain (paraphrased and example-ified):
class Car {
Engine engine
static constraints = {
engine nullable: true // poor example, I know
}
}
class Engine {
String name
}
Here's the controller action that's handling the sort:
def myAction = {
def list = Car.findAll(params)
render(view: 'list', model: [list: list])
}
I provision some data such that there are several Cars, some with null engines and others with engines that are not null.
I attempt the following query:
http://www.example.com/myController/myAction?sort=engine.name&order=asc
The results from the query only return Car entries whose engine is not null. This is different from the results that would be returned if I only queried the association (without its property):
http://www.example.com/myController/myAction?sort=engine&order=asc
which would return all of the Car results, grouping the ones with null engines together.
Is there any way that:
I can get the query that sorts by the association property to return the same results as the one that sorts by only the association (with the null associations grouped together)?
I can achieve those results using the built-in sorting passed to list() (i.e. without using a Criteria or HQL query)
You need to specify LEFT_JOIN in the query, try this:
import org.hibernate.criterion.CriteriaSpecification
...
def list = Car.createCriteria().list ([max:params.max?:10, offset: params.offset?:0 ]){
if (params.sort == 'engine.name') {
createAlias("engine","e", CriteriaSpecification.LEFT_JOIN)
order( "e.name",params.order)
} else {
order(params.sort, params.order)
}
}
Remember to put engine.name as the property to order by in your list.gsp
<g:sortableColumn property="engine.name" title="Engine Name" />

Resources