treaves,
Cypher-query-annotated methods are quite good for this:
Code:
@NodeEntity
class Foo {
@GraphId
Long id;
Bar bar;
Foo() {
}
Foo(Bar bar) {
this.bar = bar;
}
}
@NodeEntity
class Bar {
@GraphId
Long id;
}
interface FooRepository extends CRUDRepository<Foo> {
@Query("start n=node(*) return count(n)")
int countNodes();
@Query("start n=node:__types__(className=\"cypher.mutation.Bar\") match n<-[r?:bar]-m where r is null return count(n)")
int countUnconnectedBars();
@Query("start n=node:__types__(className=\"cypher.mutation.Bar\") match n<-[r?:bar]-m where r is null delete n")
void deleteUnconnectedBars();
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MutatingCypherQueriesTests {
@Configuration
@EnableNeo4jRepositories
static class TestConfig extends Neo4jConfiguration {
@Bean
GraphDatabaseService graphDatabaseService() {
return new ImpermanentGraphDatabase();
}
}
@Autowired
private GraphDatabaseService graphDatabaseService;
@Autowired
private FooRepository fooRepository;
@Autowired
private Neo4jTemplate template;
@Before
public void before() {
Neo4jHelper.cleanDb(graphDatabaseService, true);
Transaction transaction = graphDatabaseService.beginTx();
Bar bar1 = template.save(new Bar());
Bar bar2 = template.save(new Bar());
Bar bar3 = template.save(new Bar());
template.save(new Foo(bar1));
template.save(new Foo(bar1));
template.save(new Foo(bar2));
transaction.success();
transaction.finish();
}
@Test
public void shouldDeleteUnconnectedNodes() throws Exception {
assertThat(fooRepository.countNodes(), is(6));
assertThat(fooRepository.countUnconnectedBars(), is(1));
Transaction transaction = graphDatabaseService.beginTx();
fooRepository.deleteUnconnectedBars();
transaction.success();
transaction.finish();
assertThat(fooRepository.countNodes(), is(5));
assertThat(fooRepository.countUnconnectedBars(), is(0));
}
}
Regards,
Lasse