【问题标题】:Neo4j Repository - Writing query with a dynamic where clauseNeo4j 存储库 - 使用动态 where 子句编写查询
【发布时间】:2013-11-13 14:47:50
【问题描述】:

我对 Neo4j 比较陌生,并且对使用 spring 在 Neo4j 中编写动态查询有疑问。 根据我的阅读,查询在扩展 GraphRepository 类的接口中使用 @Query 参数进行注释,并且动态参数作为参数提供。

但我的要求是我必须动态生成 where 子句的数量。

For example,
@Query("match n where n.__type__='com.connectme.domain.Person' and n.age > {0} return n.id)
public List<Object> getPeopleWithAge(Integer age);//

我的查询也可以改变,其中年龄也可以小于某个值,在这种情况下,查询可以变成:

@Query("match n where n.__type__='com.connectme.domain.Person' and n.age > {0} and n.age <{1} return n.id)
public List<Object> getPeopleWithAge(Integer age1, Integer age2);//

以类似的方式,围绕年龄参数的许多子句会导致 where 子句的变化。 我如何动态处理这个问题,因为目前我只知道这种带注释的执行查询的方式。 我可以覆盖并编写自己的自定义查询吗?

【问题讨论】:

  • 您也可以使用 Neo4j-Template.query 进行自定义查询或从 CypherDslRepository 继承并使用 CypherDSL
  • 您能详细说明一下吗?我不熟悉 CypherDslREpository 是什么?

标签: neo4j cypher spring-data-neo4j


【解决方案1】:

您可以编写自己的自定义查询逻辑。首先,您创建一个包含自定义查询方法的额外接口,因此您将获得两个存储库接口

public interface YourRepository extends GraphRepository<SomeClass> implements YourRepositoryExtension{
    //inferred queries, annotated queries
}


public interface YourRepositoryExtension {
    EndResult<SomeClass> customQuery();
    Iterable<SomeClass> customTraversal();
}

然后你做一个实现:

@Repository
public class YourRepositoryImpl implements YourRepositoryExtension {

    @Autowired
    private YourRepository yourRepository;

    @Override
    public EndResult<SomeClass> customQuery(){
        //your query logic, using yourRepository to make cypher calls.
        return yourRepository.query("START n.. etc.. RETURN n", <optional params>);
    }

    @Override
    public Iterable<SomeClass> customTraversal(){
        SomeClass startNode = yourRepository.findOne(123);
        return yourRepository.findAllByTraversal(startNode, <some custom traversal>);
    }
}

【讨论】:

  • 感谢您的回复...但我还没有完全理解这一点...我该如何编写查询,我必须在 YourRepositoryImpl 类中实现 GraphRepository 吗?
  • 我已将示例更新为更详细。现在更清楚了吗?
  • 抱歉回复晚了..但非常感谢您的解释。解决了困扰我一段时间的问题。
  • @Wouter 不幸的是,这种方法不再有效,因为 GraphRepository 不再包含查询或 findAllByTraversal 方法。你碰巧有针对 spring-neo4j v. 5.1 的这个问题的解决方案吗?
猜你喜欢
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多