Search code examples
ioscore-datagraphframeworkscosmicmind

CosmicMind/Graph: Search for Specific Related Entities


Hi all,

looking for support for a CoreData wrapper framework called Graph from CosmicMind (https://github.com/CosmicMind/Graph).

There's unfortunately rather little documentation beyond the absolute basics (though there seem to be a lot of quite powerful concepts introduced b.t.w.).

I wonder if somebody could - please - help me out with how to select/filter Entities in a 1:N relationship.

Given the following structure...

import Graph

let graph = Graph()
graph.clear()

let sectionA = Entity(type: "Section")
sectionA["id"] = 12
sectionA["name"] = "SectionA"

let sectionB = Entity(type: "Section")
sectionB["id"] = 2
sectionB["name"] = "SectionB"

let unitA = Entity(type: "Unit")
unitA["id"] = 122
unitA["name"] = "UnitA"
unitA["isExpensive"] = false
unitA.is(relationship: "UnitOfSection").of(sectionA)

let unitB = Entity(type: "Unit")
unitB["id"] = 19
unitB["name"] = "UnitB"
unitB["isExpensive"] = false
unitB.is(relationship: "UnitOfSection").of(sectionB)

let unitC = Entity(type: "Unit")
unitC["id"] = 7
unitC["name"] = "UnitC"
unitC["isExpensive"] = true
unitC.is(relationship: "UnitOfSection").of(sectionA)

let unitD = Entity(type: "Unit")
unitD["name"] = "UnitD"
unitD["isExpensive"] = true
unitD["id"] = 4
unitD.is(relationship: "UnitOfSection").of(sectionA)

graph.sync()

let unitsSearch = Search<Entity>(graph: graph).for(types: "Unit")
let units = unitsSearch.sync()

... I'd like to get only those Entities which have a "UnitOfSection" relationship to sectionA AND which have a property "isExpensive" with value false.

Any idea how to achieve this?

Thanks + best whishes


Solution

  • This should work:

    let units = Search<Entity>(graph: graph).for(types: "Unit").sync().filter { entity in
        (entity["isExpensive"] as? Bool) == false && 
        entity.relationship(types: "UnitOfSection").contains(where: { relationship in
            relationship.object == sectionA
        })
    }
    

    What we do is:

    1. Fetch all "Unit" Entities
    2. Filter entities that has isExpensive = false
    3. And fetch "UnitOfSection" relationships of each entity and test if that relationship's object is sectionA