How to query based on one-to-many relationships in Spring Data Neo4j

359 views Asked by At

I have defined simple one-to-many relationship as:

@Relationship(type = "BELONG")
private Set<Category> categories;

I want to query all the objects based on the exact set of Category. i.e. implement something like:

Page<SomeObject> findAllByCategories(Set<Category> categories, PageRequest page);

What is the best way to do it in Spring Data Neo4j?

1

There are 1 answers

2
digx1 On

You have a couple of options on how you can do this.

Your calling code can simply call the following on your SomeObjectRepository:

Iterable<Long> ids = categories.stream().map(SomeObject::getId).collect(Collectors.toSet());
Iterable<SomeObject> someObjects = someObjectRepository.findAll(ids, 1);

Note this method does not support paging though.

Another way is to inject a Session into your calling code and either write a custom Cypher query to retrieve the objects you want or use the load all by instance method:

@Autowired
private Session session;

...

// Option 1: write some cypher
Map<String, Object> params = new HashMap<>():
params.put("ids", ids) // use a stream like above to collect the ids.
Iterable<SomeObject> someObjects = session.query(SomeObject.class, "MATCH (n:SomeObject) ...", params);

//Option 2: use the load by instances method which also allows pagination:
Collection<SomeObject> someObjects = session.loadAll(categories, new Pagination(0, 25));

My recommendation would be option 2 as it pretty much does exactly what you want.