How to count query with hint on Spring mongoTemplate? - spring

...
Query query = new Query().addCriteria(...);
query.withHint("Index name");
mongoTemplate.count(query, MyClass.class);
...
This count query code doesn't seem to apply hint.
How can I apply index hint to count query on MongoTemplate?

Related

Why are there two queries in one annotation?

Below is an example from the Spring Data and Neo4j documentation, which demonstrates the usage of cypher queries.
// returns a Page of Actors that have a ACTS_IN relationship to the movie node with the title equal to movieTitle parameter.
#Query(value = "MATCH (movie:Movie {title={0}})<-[:ACTS_IN]-(actor) RETURN actor", countQuery= "MATCH (movie:Movie {title={0}})<-[:ACTS_IN]-(actor) RETURN count(actor)")
Page<Actor> getActorsThatActInMovieFromTitle(String movieTitle, PageRequest page);
what's the use of the second query "countQuery=..."? Does it play any role in this query?
The usage is mentioned in the documentation here. The relevant section:
If it is required that paged results return the correct total count,
the #Query annotation can be supplied with a count query in the
countQuery attribute. This query is executed separately after the
result query and its result is used to populate the number of elements
on the Page.

Sortorder in Elasticsearch

I have written elasticsearch query using java api in which status count is fetched per day.
Code:
SearchResponse responseOutput = client.prepareSearch(ConstantsValue.indexName)
.setTypes(ConstantsValue._Type)
.setFetchSource(new String[]{"STATUS", "DTCREATED"}, null)
.setQuery(
QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
FilterBuilders.rangeFilter("DTCREATED").from(fromDate).to(toDate))).
addAggregation(AggregationBuilders.terms("STATUS_AGG").field("STATUS")
.subAggregation(AggregationBuilders.dateHistogram("DATE_AGG").field("DTCREATED").interval(DateHistogram.Interval.DAY).format("yyyy-MM-dd"))
)
.addSort("DTCREATED", SortOrder.ASC)
.get();
I am trying to sort data by DTCREATED field which contains both date and time but query does not provide sorted result. I can't find what I am missing in query. Any help ?
What if you have your .addSort as below:
.addSort(SortBuilders.fieldSort("DTCREATED").order(SortOrder.ASC))
Few samples here might help you.

How can we fetch column values which are between two limits in MongoTemplate?

for example i want to find age between 16 and 25 from a collection in mongoDB.
my query is..
Query query = new Query(Criteria.where("visibility").is(1)
.and("type").is("guide").and("age").gte(16).and("age").lte(25));
but it is giving exception. reason is mongo template do not support lte() and gte() with same column. so how can i handle it ? is their any solution ?
Try not to include an extra and("age") part in your criteria. What you need is this:
Query query = new Query(Criteria.where("visibility").is(1)
.and("type").is("guide").and("age").gte(16).lte(25));

Spring Mongo criteria problems with andOperator

I'm trying to create a dynamic mongoDB query using spring Criteria. My query is :
Criteria.where(key1).is(value1).and(key2).is(value2)
The numbers of key/value is not fixed but can change.
I try to use andOperator but it's not for my case.
Can someone help me?
This post explains a similara problem:
Spring Mongo criteria querying twice the same field
This is what you want to do:
Criteria criteria = new Criteria().andOperator(
Criteria.where("key1").is(value1),
Criteria.where("key2").is(value2));
// to print the mongodb query for debug purposes
// System.out.println(criteria.getCriteriaObject());
// execute with a mongoTemplate
List<YourClass> documents = mongoTemplate.find(new Query(criteria), YourClass.class);

How to get total count in hibernate full text search?

I am trying using hibernate full text by following this link:
hibernate/search/4.1/reference/en-US/html/getting-started
Basically, it works, but I want to know how to get total count while I execute a full text query,then I can tell user how many results and how many pages would be in such a query.
Here is the code(Using JPA to create and execute a search):
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager =
org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
em.getTransaction().begin();
// create native Lucene query unsing the query DSL
// alternatively you can write the Lucene query using the Lucene query parser
// or the Lucene programmatic API. The Hibernate Search DSL is recommended though
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity( Book.class ).get();
org.apache.lucene.search.Query query = qb
.keyword()
.onFields("title", "subtitle", "authors.name", "publicationDate")
.matching("Java rocks!")
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, Book.class);
persistenceQuery.setFirstResult((page - 1) * PAGECOUNT);
persistenceQuery.setMaxResults(PAGECOUNT);
// execute search
List result = persistenceQuery.getResultList();
em.getTransaction().commit();
em.close();
In SQL, I can use select count(*) from something, but here I don't know how to do that. I want to just fetch one page of data every time and use another API to get total count.
query.getResultSize(); //return the total number of matching ... regardless of pagination
I'm not sure if there is such a way when using the Hibernate full text search.
If you want to know the total number of results then you have to perform the full query. After you have the full count you can set your page limiter and perform it again.
javax.persistence.Query persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, Book.class);
int count = persistenceQuery.getResultList().size();
persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, Book.class);
persistenceQuery.setFirstResult((page - 1) * PAGECOUNT);
persistenceQuery.setMaxResults(PAGECOUNT);
List result = persistenceQuery.getResultList();
For Hibernate(maybe for JPA)
public interface FullTextQuery extends Query
in other words, you need use
org.hibernate.search.FullTextQuery query = fullTextEntityManager.createFullTextQuery(query, Book.class);
instead of
org.hibernate.Query query = fullTextEntityManager.createFullTextQuery(query, Book.class);
and method getResultSize() will be available
When using directly Lucene/Solr, I usually use a hack* by searching for *:*, setting it to return the least possible results BUT that does return the total result count for "everything", and I proceed to extract it. Basically it's the same as the SELECT count(*) FROM whatever :P
*I say hack because I'm not sure if it's supposed to be that way or not, but it works for me...

Resources