MATCH (sellerCompanyTopic:Company)-[rel:Seller]->(sr:SalesRelation)-[rel2:Buyer]-(buyer:Company),
sr<-[:PriceAgreement]-(contract:Contract)
MATCH (rootTopic:Company) WHERE rootTopic.ID = 172096
OPTIONAL MATCH p = shortestPath(rootTopic-[:Seller|Buyer*]-sellerCompanyTopic)
WITH rootTopic, sellerCompanyTopic, buyer, contract,
reduce(
index = 0,
type IN EXTRACT(r in relationships(p) | type(r))|
case
when index % 2 = 0 AND type = 'Buyer'
then -1000
when index % 2 = 1 AND type = 'Seller'
then -1000
ELSE index + 1
END
) AS Related
WHERE rootTopic = sellerCompanyTopic OR rootTopic = buyer OR Related > 0
RETURN rootTopic.ID AS RootCompanyTopicID, sellerCompanyTopic.ID AS SellerTopicID, buyer.ID AS BuyerTopicID, contract.ID AS ContractTopicID, case
when Related is null
then 1
when Related < 0
then 0
ELSE Related
END AS Depth
ORDER BY RootCompanyTopicID, SellerTopicID, BuyerTopicID, ContractTopicID