Spring data mongodb: query and sort results based on difference of two fields - spring-data

Say I have a Collection defined like bellow:
#Document(collection = "Item")
public class Item {
#Id
private String id;
private String title;
private String mrp;
private String discount;
//getters and setters goes here
}
I need to find all items which are sorted on [mrp - discount] value.
How to express this using MongoOperations

That's what the Aggregation Framework is for. Spring Data MongoDB offers aggregate via MongoOperations.
TypedAggregation<Item> agg = newAggregation(Item.class,
project()
.andExpression("mrp - discount").as("total")
.andInclude("mrp", "discount", "id"),
sort(new Sort(ASC, "total")));

Related

How to append where clause to all queries that run with spring data MongoRepository?

I have entities that are persisted in MongoDB and use spring data MongoRepository to fetch data. Now i want to apply filter to all queries that executed on the entites, so i decided to use hibernate filter, something like this:
#Entity
#QueryEntity
#Document(collection = "Opportunity")
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
#CompoundIndexes({
#CompoundIndex(name = "productGroup_userId_uniqueness", def = "{'productGroupCode' : 1, 'userId': 1}", unique = true)
})
#FilterDef(name = "defaultFilter",parameters = #ParamDef(name = "unitCode",type = "string"))
#Filter(name = "defaultFilter" , condition = " unitCode like :unitCode")
public class Opportunity {
#Id
#Indexed
private String id;
#Indexed
#Enumerated(EnumType.STRING)
private OpportunityStatus opportunityStatus = OpportunityStatus.OPEN;
private LeadType leadType;
#Indexed
private String userId;
#Indexed
private String productCode;
#Indexed
private String productGroupCode;
#Indexed
private Long actionId;
private String assigneeId;
#Transient
private List<AbstractCommand> commandHistory = new ArrayList<>();
#Transient
private Map<Long, Boolean> actionStatus = new HashMap<>();
private String unitCode;
}
and this is the repository class:
#Repository
public interface OpportunityRepository extends MongoRepository<Opportunity, String>, QuerydslPredicateExecutor<Opportunity> {
// this repository contains more than 20 methods
// and all of theme removed for question brevity
}
And I enabled hibernate filter on session with this way:
Session session = (entityManager).unwrap(Session.class);
session.enableFilter(filterName).setParameter("unitCode", this.getCurrentUserUnitCode());
Now, when I call OpportunityRepository.findAll(Predicate predicate, Pageable pageable) i expected to apply the defined filter on the entity, but it didn't work.
I think the reason is that MongoRepository hasn't any sense of hibernate #Filter and i should use another way to append where clause to all mongo queries that running on the Opportunity entity.

Can I mark more than one field as #indexed in single document in MongoDb?

I am using #indexed annotation in my document for the person while using spring boot and MongoDb.
I have already marked firstName to be used for indexing.
Can I mark other fields as well for index?
The document is as mentioned below:
#Document
public class Person {
#Id private String id;
#Indexed(name = "first_name_index", direction = IndexDirection.DESCENDING)
private String firstName;
private String secondName;
private LocalDateTime dateOfBirth
}
Is it a good practice to mark more than one field as indexed?
Yes. You can index multiple fields as #Indexed if your queries are orthogonal.
You need to support findByFirstName and findByDateOfBirth queries.
you add #Indexed annotation to firstName
you add #Indexed annotation to dateOfBirth
You need to support findByFirstName and findByFirstNameAndDateOfBirth queries.
you add #CompoundIndex(def = "{'findByFirstName': 1, 'dateOfBirth': 1}") to public class Person.

Spring boot store dynamic key value pair list in mongodb

I am using spring boot. I want to store dynamic collection with name value pair using model in mondo db.
How to store below json in mongodb?
{
"id":"123456",
"name":"test",
"attributes":[
{"name":"1"},
{"color":"red"},
{"size":"small"}
],
.....
}
Here attributes is dynamic hashmap.
how to create model in spring boot for above?
public class Records {
#Id
String id;
#Field("name")
String name;
#Field("attributes")
private BasicDBObject variantAttrs;
}
above is creating json object of attributes and not json array.
Instead of mapping an array of attributes to BasicDBObject, we need to map it to List.
public class Records {
#Id
String id;
#Field("name")
String name;
#Field("attributes")
private List<BasicDBObject> variantAttrs;
}

Hibernate Search Tuple Queries

I have an entity Message with a one-to-many relation to an entity Header. How can I create a tuple based search query like
(message.headerKey="foo" and message.headerValue="123") and
(message.headerKey="bar" and message.headerValue="456")
My current logic would also match when I swap the header values in my search criteria
(message.headerKey="foo" and message.headerValue="456") and
(message.headerKey="bar" and message.headerValue="123")
How can I do a tuple based query using the Hibernate Search API?
This is my Message Entity:
#Entity
#Table(name="MESSAGE")
#Indexed
public class MessageEntity implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private Long id;
#Column(name="message_timestamp")
private Date timestamp;
#Column(name="payload")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String payload;
#OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "message")
#IndexedEmbedded
private List<HeaderEntity> headers;
// Getters and Setters
}
This is my Header Entity:
#Entity
#Table(name="HEADER")
public class HeaderEntity implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Column(name="header_key")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String headerKey;
#Column(name="header_value")
Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String headerValue;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="message_id")
private MessageEntity message;
// Getters and Setters
}
This is my search logic:
public List<MessageEntity> search(Header[] headers) {
FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(mgr);
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(MessageEntity.class).get();
TermMatchingContext onFieldKey = qb.keyword().onField("headers.headerKey");
TermMatchingContext onFieldValue = qb.keyword().onField("headers.headerValue");
BooleanJunction<BooleanJunction> bool = qb.bool();
org.apache.lucene.search.Query query = null;
for (Header header : headers) {
bool.must(onFieldKey.matching(header.getKey()).createQuery());
bool.must(onFieldValue.matching(header.getValue()).createQuery());
}
query = bool.createQuery();
FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query, MessageEntity.class);
persistenceQuery.setMaxResults(10);
return persistenceQuery.getResultList();
}
Your approach will indeed not work. The problem is that Lucene is a flat data structure, in particular associations (embedded entities) are just "added" to the Lucene Document of the owning entity. In your case the MessageEntity document will contain two fields per headerKey respectively headerValue. Once with "foo" and "bar" as value and56" as values. once with "123" and "456" as values. There is no notion that two of these values are acutally a pair.
One potential solution is to create a unique field/value pair. Using a custom class bridge you could create a "keyValueField" containing header key and value as concatenated value. In your query you would then target this field using concatenated query parameters.

Query an embedded collection inside an entity using Datanucleus and mongodb

I was trying to query a embedded collection inside an entity using a query similar to the following:
Query q = em.createQuery("SELECT u FROM User u , in (u.addresses) a
WHERE a.state='xx'");
The query didn't return any result nor did it throw any error. I am using Datanucleus and MongoDb. Does Datanucleus have any limitation on such queries?
And the entity looked like:
public class User{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
protected long id;
#ElementCollection
protected List<Address> addresses;
public User(){
}
...
#Embeddable
public class Address {
private String street;
private String city;
private String state;
private Integer zip;
public Address(){
}
...