假设我们使用这个简单的图模型:
@NodeEntity
class Ad {
// GraphId and more Ad attributes...
@Relationship(type = "HAS_ADVERTISER", direction = Relationship.OUTGOING)
private User advertiser;
@Relationship(type = "IS_FAVOURITE_TO", direction = Relationship.OUTGOING)
private Set<User> favourites = new HashSet<>();
// Getters and setters
}
编辑 :根据其中一个aswers的建议,我尝试将传入关系添加到用户实体,但问题仍然存在。
@NodeEntity
class User {
// User attributes. No incoming relationships for HAS_ADVERTISER neither IS_FAVOURITE_TO...
// EDIT: Added incoming relationships to User entity, but the problem still remains. Tried annotating getters/setters, but neither works
@Relationship(type = "HAS_ADVERTISER", direction = Relationship.INCOMING)
private Set<Ad> ads = new HashSet<>();
@Relationship(type = "IS_FAVOURITE_TO", direction = Relationship.INCOMING)
private Set<Ad> favourites = new HashSet<>();
@Relationship(direction = Relationship.INCOMING)
public Set<Ad> getAds() {
return ads;
}
@Relationship(direction = Relationship.INCOMING)
public void setAds(Set<Ad> ads) {
this.ads = ads;
}
@Relationship(direction = Relationship.INCOMING)
public Set<Ad> getFavourites() {
return favourites;
}
@Relationship(direction = Relationship.INCOMING)
public void setFavourites(Set<Ad> favourites) {
this.favourites = favourites;
}
}
如果我通过neo4j控制台执行cypher查询以检索包含广告客户和收藏夹信息的广告,那么它只是运作良好:
MATCH (ad:Ad),
(ad)-[has_advertiser:HAS_ADVERTISER]->(advertiser:User),
(ad)-[is_favourite_to: IS_FAVOURITE_TO] -> (favouriteUser:User)
return ad, has_advertiser, advertiser, is_favourite_to, favouriteUser
但是,如果我通过neo4jRepository
执行查询:
advertiser
用户已正确保留。favourites
集中有两个用户:广告客户用户总是被添加到集合中,这是不正确的,因为与该用户没有IS_FAVOURITE_TO
的关系。@Repository
public interface AdRepository extends Neo4jRepository<Ad> {
@Query("MATCH (ad:Ad)," +
"(ad)-[has_advertiser:HAS_ADVERTISER]->(advertiser:User)," +
"(ad)-[is_favourite_to: IS_FAVOURITE_TO] -> (favouriteUser:User)" +
"return ad, has_advertiser, advertiser, " +
"is_favourite_to, favouriteUser ")
List<Ad> findAds();
}
我可以更改查询或图表模型中的内容以避免这种情况吗? 也许是spring-data-neo4j bug?
版本:
<spring-data-neo4j.version>4.2.0.M1</spring-data-neo4j.version>
<neo4j.ogm.version>2.0.5</neo4j.ogm.version>
答案 0 :(得分:2)
这是因为OGM认为这是一个模棱两可的模型。如果您将传入关系添加到User
,则应解决您的问题。
更新:经过进一步调查,这确实是一个错误。已打开https://github.com/neo4j/neo4j-ogm/issues/276
解决方法是在广告和用户中注释所有的getter和setter(并确保@Relationship注释包含关系类型和方向)。
答案 1 :(得分:0)
当您返回Ad
节点时,Spring Data不会填充嵌入式节点。你需要一个专门的结果。此外,在您的查询中,您将返回has_advertiser
类中没有映射的is_favourite_to
和Ad
关系。他们完全无关紧要。将您的查询更改为
@Query("MATCH (advertiser:User)<-[:HAS_ADVERTISER]-(a:Ad)-[:IS_FAVOURITE_TO]->(favourite:User)
RETURN a AS ad, advertiser, collect(DISTINCT favourite) AS favourites")
public List<AdWithAdvertiserAndFavouritesResult getAdsWithAdvertisersAndFavourites()
然后是
@QueryResult
public class AdWithAdvertiserAndFavouritesResult {
private Ad ad;
private User advertiser;
private List<User> favourites;
//only getters, no setters
}
您可能需要考虑为Ad
定义一个唯一的附加属性,该属性可以在以后用作索引,因为查询不会扩展并导致重负载:您始终匹配整个集合Ad
个节点。我强烈建议不要这样做。