UNWIND $keys AS id MATCH (p:Product:Orchard { upc: id }) OPTIONAL MATCH (ppcs:PublicProduct:ChartmetricSpotify {upc:p.upc}) WITH id, p, COLLECT({releaseDate: ppcs.releaseDate, imageUrl: ppcs.imageUrl}) AS spotifyItems OPTIONAL MATCH (ppca:PublicProduct:ChartmetricAppleMusic {upc:p.upc}) WITH id, p, spotifyItems, COLLECT({releaseDate: ppca.releaseDate, imageUrl: ppca.imageUrl}) AS appleMusicItems OPTIONAL MATCH (pp:PublicProduct {upc:p.upc}) WHERE NOT (pp:ChartmetricAppleMusic OR pp:ChartmetricSpotify) WITH id, p, spotifyItems, appleMusicItems, COLLECT({releaseDate: pp.releaseDate, imageUrl: pp.imageUrl}) as otherItems WITH id, p, HEAD(apoc.coll.sortMaps(spotifyItems, "^releaseDate")) AS spotifyItem, HEAD(apoc.coll.sortMaps(appleMusicItems, "^releaseDate")) AS appleMusicItem, HEAD(apoc.coll.sortMaps(otherItems, "^releaseDate")) AS otherItem RETURN id, COALESCE(spotifyItem.imageUrl, appleMusicItem.imageUrl, otherItem.imageUrl, p.imageUrl)