How does the #Relationship annotation in Spring Data Neo4j order the results? - spring-data-neo4j

I would like to order the returned outgoing nodes in a specific way, based on a relationship property. Can this customized at all? I can't even find anything in the docs about what the default ordering is.
#Relationship("CREATED")
private List<Node> nodes;

There is no default sorting in Spring Data Neo4j.
Also there is no default sorting in the database.
You should not make any assumptions if there is no explicit ordering in the query.
If you want to go the path in Cypher you have to define a custom query.
For this, I am referring to the movie graph (:play movies) to populate the database and have some example data.
If you would call:
MATCH (m:Movie{title:'The Matrix'}) OPTIONAL MATCH (m)<-[:ACTED_IN]-(p) return m, collect(p)
The actors will have a random order.
But if you add ordering by e.g. the actor's name to this, you get the desired result.
MATCH (m:Movie{title:'The Matrix'}) OPTIONAL MATCH (m)<-[:ACTED_IN]-(p) WITH m, p ORDER BY p.name return m, collect(p)

Related

Ordered list in Django

Can anyone help, I want to return an ordered list based on forloop in Django using a field in the model that contains both integer and string in the format MM/1234. The loop should return the values with the least interger(1234) in ascending order in the html template.
Ideally you want to change the model to have two fields, one integer and one string, so you can code a queryset with ordering based on the integer one. You can then define a property of the model to return the self.MM+"/"+str( self.nn) composite value if you often need to use that. But if it's somebody else's database schema, this may not be an option.
In which case you'll have to convert your queryset into a list (which reads all the data rows at once) and then sort the list in Python rather than in the database. You can run out of memory or bring your server to its knees if the list contains millions of objects. count=qs.count() is a DB operation that won't.
qs = Foo.objects.filter( your_selection_criteria)
# you might want to count this before the next step, and chicken out if too many
# also this simple key function will crash if there's ever no "/" in that_field
all_obj = sorted( list( qs),
key = lambda obj: obj.that_field.split('/')[1] )

Filter models on the basis of dictionary key

I am facing a problem while filtering a record from the database. In my database I have records which contain a dictfield.
for eg
region is a dictionary which contains other dictionaries like
region = {'eastus': {'percentage_change': 0}, 'westus': {'percentage_change': 0}}
and I want to fetch eastus or westus.
I have tried something like this, but I am getting an empty list.
MyModel.objects.filter(region__eq='eastus')
any suggestions for this problem?
I believe you can achieve this with the exists operator (http://docs.mongoengine.org/guide/querying.html#query-operators)
MyModel.objects.filter(region__eastus__exists=True)
Regarding the OR, you should use the Q class (http://docs.mongoengine.org/guide/querying.html#advanced-queries), thus:
MyModel.objects.filter(Q(region__eastus__exists=True) | Q(region__westus__exists=True))
If you have keys that aren't simple (e.g including fancy character or simply a dash), you can use the __raw__ operator:
MyModel.objects.filter(__raw__={'region.a-fancy-key': {'$exists': True}})

Return object when aggregating grouped fields in Django

Assuming the following example model:
# models.py
class event(models.Model):
location = models.CharField(max_length=10)
type = models.CharField(max_length=10)
date = models.DateTimeField()
attendance = models.IntegerField()
I want to get the attendance number for the latest date of each event location and type combination, using Django ORM. According to the Django Aggregation documentation, we can achieve something close to this, using values preceding the annotation.
... the original results are grouped according to the unique combinations of the fields specified in the values() clause. An annotation is then provided for each unique group; the annotation is computed over all members of the group.
So using the example model, we can write:
event.objects.values('location', 'type').annotate(latest_date=Max('date'))
which does indeed group events by location and type, but does not return the attendance field, which is the desired behavior.
Another approach I tried was to use distinct i.e.:
event.objects.distinct('location', 'type').annotate(latest_date=Max('date'))
but I get an error
NotImplementedError: annotate() + distinct(fields) is not implemented.
I found some answers which rely on database specific features of Django, but I would like to find a solution which is agnostic to the underlying relational database.
Alright, I think this one might actually work for you. It is based upon an assumption, which I think is correct.
When you create your model object, they should all be unique. It seems highly unlikely that that you would have two events on the same date, in the same location of the same type. So with that assumption, let's begin: (as a formatting note, class Names tend to start with capital letters to differentiate between classes and variables or instances.)
# First you get your desired events with your criteria.
results = Event.objects.values('location', 'type').annotate(latest_date=Max('date'))
# Make an empty 'list' to store the values you want.
results_list = []
# Then iterate through your 'results' looking up objects
# you want and populating the list.
for r in results:
result = Event.objects.get(location=r['location'], type=r['type'], date=r['latest_date'])
results_list.append(result)
# Now you have a list of objects that you can do whatever you want with.
You might have to look up the exact output of the Max(Date), but this should get you on the right path.

Predicate query nested fetch

I have list of predicates and use them as below.
criteriaQuery = criteriaQuery.where(builder.and(toArray(predicates, Predicate.class)));
I use the fetch for lazy as below for Person entity.
Root<Employment> root = criteriaQuery.from(type);
root.fetch(Employment_.person);
However, I need to access education entity which is mapped in Person.
I tried as below but it doesn't work.
root.fetch(Employment_.person, Person_.education);
In other words I need to do a nested fetch somehow, any suggestions?
Because at the moment if I tried to access getEmployment().getPerson().getEducation() it goes to lazy exception

Adding a DetachedCriteria-subcriteria to a projectionList

i want to construct a a pojo with some records from 2 tables using Hibernate criteria api. I'm constructing a ProjectionList with needed records from the 1st table, because i don't have a bidirectional relationship between the 2 tabls , have only from 2nd to first i've made a DetachedCriteria(subcriteria) and made a projection for the needed record.
i don't know how to add the subcriteria to the ProjectionList for having an array of the needed records
Criteria criteria = currentSession.createCriteria(getClazz());
projectionList.add(Projections.property("name"), "name");
projectionList.add(Projections.property("str"), "street");
projectionList.add(Projections.property("nr"), "nr");
DetachedCriteria subcriteria=DetachedCriteria.forClass(B.class,"b");
subcriteria.createAlias("b.adress", "adr",CriteriaSpecification.LEFT_JOIN);
subcriteria.setProjection(Projections.property("adr.id"));
Thanks!!!
If the first class has for example addressId your query can be something like that:
crteria.add(Subqueries.propertyIn("addressId", subcriteria));