diff --git a/hub3/fragments/path.go b/hub3/fragments/path.go new file mode 100644 index 00000000..a4d959b8 --- /dev/null +++ b/hub3/fragments/path.go @@ -0,0 +1,128 @@ +package fragments + +import ( + "fmt" + + "github.com/delving/hub3/ikuzo/rdf" + "github.com/delving/hub3/ikuzo/rdf/index" + elastic "github.com/olivere/elastic/v7" +) + +// PathHop is one hop of a ResourcePath: the search label of a predicate and +// the classes of the resource it starts from, one of which it must have +// (none: any class). +type PathHop struct { + SearchLabel string + SubjectClasses []string +} + +// ResourcePath is a route through a record's resources in the path syntax of +// ikuzo/rdf/index (path_query_syntax.md): [class]predicate pairs joined by +// ->, where a class names the resource that has the predicate, [] is any +// class and alternatives are separated by |. For example +// +// []schema:creator->[schema:Role]schema:creator->[schema:Person|schema:Organization]schema:name +// +// is the name of a person or organisation that is the creator of a role that +// is the object's creator. A path that ends with a predicate ends at a +// literal (Property) of the last resource; one that ends with [class] ends at +// that resource itself. +// +// The index keeps every linked resource as a nested resources element with +// its route from the root in resources.context: an element per hop with its +// Level, the predicate's SearchLabel and the SubjectClass of the resource the +// hop starts from, which is what [class]predicate says. So the resource at +// the end of a path is one resources element whose context matches the hops, +// which is what lets several conditions hold for the same linked resource. +// This generalises QueryFilter's single Level2 hop. +type ResourcePath struct { + Hops []PathHop + Classes []string // of the resource at the end + Property string // a literal of it, or "" for the resource itself +} + +// ParseResourcePath reads a path in the syntax of ikuzo/rdf/index. +func ParseResourcePath(s string) (*ResourcePath, error) { + entries, err := index.ParsePath(s, true) + if err != nil { + return nil, fmt.Errorf("path %q: %w", s, err) + } + p := &ResourcePath{} + for i, e := range entries { + last := i == len(entries)-1 + if !last && e.Predicate == "" { + return nil, fmt.Errorf("path %q: step %d has a class but no predicate", s, i+1) + } + var label string + if e.Predicate != "" { + if label, err = rdf.DefaultNamespaceManager.GetSearchLabel(e.Predicate); err != nil { + return nil, fmt.Errorf("path %q: predicate %s: %w", s, e.Predicate, err) + } + } + if !last { + p.Hops = append(p.Hops, PathHop{SearchLabel: label, SubjectClasses: e.Classes()}) + continue + } + p.Classes, p.Property = e.Classes(), label + } + return p, nil +} + +// Depth is the number of hops. +func (p *ResourcePath) Depth() int { return len(p.Hops) } + +// ResourceQuery matches records with a resource at the end of the hops for +// which all inner queries hold, such as EntryQuery for its literals at level +// Depth()+1. Without hops that resource is the record's root. +func (p *ResourcePath) ResourceQuery(inner ...elastic.Query) elastic.Query { + var must []elastic.Query + for i, h := range p.Hops { + hop := []elastic.Query{ + elastic.NewTermQuery("resources.context.Level", i+1), + elastic.NewTermQuery("resources.context.SearchLabel", h.SearchLabel), + } + if len(h.SubjectClasses) > 0 { + hop = append(hop, termsQuery("resources.context.SubjectClass", h.SubjectClasses)) + } + must = append(must, elastic.NewNestedQuery("resources.context", elastic.NewBoolQuery().Must(hop...))) + } + if len(p.Classes) > 0 { + must = append(must, termsQuery("resources.types", p.Classes)) + } + must = append(must, inner...) + return elastic.NewNestedQuery("resources", elastic.NewBoolQuery().Must(must...)) +} + +// ValueQuery matches records whose path ends in one of values: a literal of +// Property, or for a path that ends at a resource, its URI. Without values it +// matches records where the path exists. +func (p *ResourcePath) ValueQuery(values ...string) elastic.Query { + if p.Property != "" { + return p.ResourceQuery(EntryQuery(p.Property, p.Depth()+1, values...)) + } + if len(values) == 0 { + return p.ResourceQuery() + } + return p.ResourceQuery(termsQuery("resources.id", values)) +} + +// EntryQuery matches a resource with a literal of the predicate searchLabel +// at level (0: any level) that is one of values (none: any value). +func EntryQuery(searchLabel string, level int, values ...string) elastic.Query { + must := []elastic.Query{elastic.NewTermQuery(entriesSearchLabel, searchLabel)} + if level > 0 { + must = append(must, elastic.NewTermQuery("resources.entries.level", level)) + } + if len(values) > 0 { + must = append(must, termsQuery("resources.entries.@value.keyword", values)) + } + return elastic.NewNestedQuery(resourcesEntries, elastic.NewBoolQuery().Must(must...)) +} + +func termsQuery(field string, values []string) elastic.Query { + vs := make([]any, len(values)) + for i, v := range values { + vs[i] = v + } + return elastic.NewTermsQuery(field, vs...) +} diff --git a/hub3/fragments/path_test.go b/hub3/fragments/path_test.go new file mode 100644 index 00000000..cc5b09eb --- /dev/null +++ b/hub3/fragments/path_test.go @@ -0,0 +1,150 @@ +package fragments + +import ( + "encoding/json" + "reflect" + "testing" + + elastic "github.com/olivere/elastic/v7" +) + +const ( + role = "https://schema.org/Role" + person = "https://schema.org/Person" + org = "https://schema.org/Organization" +) + +func TestParseResourcePath(t *testing.T) { + for _, tc := range []struct { + in string + want ResourcePath + }{ + {"[]schema:creator->[schema:Role]schema:creator->[schema:Person|schema:Organization]schema:name", ResourcePath{ + Hops: []PathHop{{SearchLabel: "schema_creator"}, {"schema_creator", []string{role}}}, + Classes: []string{person, org}, + Property: "schema_name", + }}, + {"[schema:VisualArtwork]schema:creator->[]schema:name", ResourcePath{ + Hops: []PathHop{{"schema_creator", []string{"https://schema.org/VisualArtwork"}}}, + Property: "schema_name", + }}, + {"[]schema:creator->[schema:Person]", ResourcePath{Hops: []PathHop{{SearchLabel: "schema_creator"}}, Classes: []string{person}}}, + {"schema:name", ResourcePath{Property: "schema_name"}}, + {"[" + person + "]schema:name", ResourcePath{Classes: []string{person}, Property: "schema_name"}}, + } { + got, err := ParseResourcePath(tc.in) + if err != nil { + t.Errorf("%s: %v", tc.in, err) + continue + } + if !reflect.DeepEqual(*got, tc.want) { + t.Errorf("%s:\n got %+v\nwant %+v", tc.in, *got, tc.want) + } + } + for _, bad := range []string{"", "[schema:Person", "[]->[schema:Person]schema:name", "[nope:X]schema:name", + "[schema:Person||schema:Organization]schema:name", "[]nope:creator"} { + if _, err := ParseResourcePath(bad); err == nil { + t.Errorf("%q parsed", bad) + } + } +} + +func sourceJSON(t *testing.T, q elastic.Query) string { + t.Helper() + src, err := q.Source() + if err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(src) + return string(b) +} + +func asJSON(t *testing.T, v any) string { + t.Helper() + b, _ := json.Marshal(v) + return string(b) +} + +// nested is a nested bool query as olivere writes it: one must clause as +// an object, more as a list. +func nested(path string, must ...any) map[string]any { + var m any = must + if len(must) == 1 { + m = must[0] + } + return map[string]any{"nested": map[string]any{"path": path, "query": map[string]any{"bool": map[string]any{"must": m}}}} +} + +func term(field string, v any) map[string]any { + return map[string]any{"term": map[string]any{field: v}} +} + +func terms(field string, vs ...any) map[string]any { + return map[string]any{"terms": map[string]any{field: vs}} +} + +// The resource at the end of a path is one nested resources element: each hop +// is a context condition at its level, the class after a hop is the +// SubjectClass of the next level's context or, at the end, the resource's +// own types, and the value is an entry one level below the resource. +func TestResourcePathQueries(t *testing.T) { + path, err := ParseResourcePath("[]schema:creator->[schema:Role]schema:creator->[schema:Person|schema:Organization]schema:name") + if err != nil { + t.Fatal(err) + } + hops := []any{ + nested("resources.context", term("resources.context.Level", 1), term("resources.context.SearchLabel", "schema_creator")), + nested("resources.context", term("resources.context.Level", 2), term("resources.context.SearchLabel", "schema_creator"), + terms("resources.context.SubjectClass", role)), + terms("resources.types", person, org), + } + entry := func(values ...any) any { + must := []any{term("resources.entries.searchLabel", "schema_name"), term("resources.entries.level", 3)} + if len(values) > 0 { + must = append(must, terms("resources.entries.@value.keyword", values...)) + } + return nested("resources.entries", must...) + } + + for name, tc := range map[string]struct { + q elastic.Query + want any + }{ + "value": {path.ValueQuery("Sphinx"), nested("resources", append(append([]any{}, hops...), entry("Sphinx"))...)}, + "one of": {path.ValueQuery("Sphinx", "Bram"), nested("resources", append(append([]any{}, hops...), entry("Sphinx", "Bram"))...)}, + "has value": {path.ValueQuery(), nested("resources", append(append([]any{}, hops...), entry())...)}, + } { + if got, want := sourceJSON(t, tc.q), asJSON(t, tc.want); got != want { + t.Errorf("%s:\n got %s\nwant %s", name, got, want) + } + } + + res := mustParse(t, "[]schema:creator->[schema:Person]") + hop := nested("resources.context", term("resources.context.Level", 1), term("resources.context.SearchLabel", "schema_creator")) + for name, tc := range map[string]struct { + q elastic.Query + want any + }{ + "is a Person": {res.ValueQuery(), nested("resources", hop, terms("resources.types", person))}, + "is that Person": {res.ValueQuery("http://x/p1"), nested("resources", hop, terms("resources.types", person), terms("resources.id", "http://x/p1"))}, + "same resource": {res.ResourceQuery(EntryQuery("schema_name", 2, "Sphinx")), nested("resources", hop, terms("resources.types", person), nested("resources.entries", term("resources.entries.searchLabel", "schema_name"), term("resources.entries.level", 2), terms("resources.entries.@value.keyword", "Sphinx")))}, + "the object itself": {mustParse(t, "schema:name").ValueQuery("Molen"), nested("resources", nested("resources.entries", term("resources.entries.searchLabel", "schema_name"), term("resources.entries.level", 1), terms("resources.entries.@value.keyword", "Molen")))}, + "root class": {mustParse(t, "[schema:VisualArtwork]schema:creator->[]schema:name").ValueQuery("Sphinx"), nested("resources", + nested("resources.context", term("resources.context.Level", 1), term("resources.context.SearchLabel", "schema_creator"), + terms("resources.context.SubjectClass", "https://schema.org/VisualArtwork")), + nested("resources.entries", term("resources.entries.searchLabel", "schema_name"), term("resources.entries.level", 2), terms("resources.entries.@value.keyword", "Sphinx")))}, + } { + if got, want := sourceJSON(t, tc.q), asJSON(t, tc.want); got != want { + t.Errorf("%s:\n got %s\nwant %s", name, got, want) + } + } +} + +func mustParse(t *testing.T, s string) *ResourcePath { + t.Helper() + p, err := ParseResourcePath(s) + if err != nil { + t.Fatal(err) + } + return p +} diff --git a/ikuzo/rdf/index/graph_query.go b/ikuzo/rdf/index/graph_query.go index 02646a6a..7d17a709 100644 --- a/ikuzo/rdf/index/graph_query.go +++ b/ikuzo/rdf/index/graph_query.go @@ -331,9 +331,12 @@ func matchesClass(resource *Resource, class string) bool { return true // Empty class matches any resource } - for _, t := range resource.Types { - if t == class { - return true + // A class may be alternatives separated by |; any of them matches. + for _, c := range strings.Split(class, "|") { + for _, t := range resource.Types { + if t == c { + return true + } } } diff --git a/ikuzo/rdf/index/path_query.go b/ikuzo/rdf/index/path_query.go index 5f4fbb43..723a367e 100644 --- a/ikuzo/rdf/index/path_query.go +++ b/ikuzo/rdf/index/path_query.go @@ -33,6 +33,15 @@ type PathEntry struct { IsLeaf bool // IsLeaf indicates that this is the last entry in the path } +// Classes are the alternatives of Class, separated by | (any of them +// matches); none for [], any class. +func (pe *PathEntry) Classes() []string { + if pe.Class == "" { + return nil + } + return strings.Split(pe.Class, "|") +} + func (pe *PathEntry) String() string { return fmt.Sprintf("[%s]%s", pe.Class, pe.Predicate) } @@ -47,10 +56,17 @@ func (pe *PathEntry) ExpandNamespace() error { } } if pe.Class != "" { - pe.Class, err = mgr.Expand(pe.Class) - if err != nil { - return fmt.Errorf("unable to expand class %s: %w", pe.Class, err) + classes := pe.Classes() + for i, class := range classes { + if class == "" { + return fmt.Errorf("empty alternative in class %s", pe.Class) + } + classes[i], err = mgr.Expand(class) + if err != nil { + return fmt.Errorf("unable to expand class %s: %w", class, err) + } } + pe.Class = strings.Join(classes, "|") } return nil diff --git a/ikuzo/rdf/index/path_query_syntax.md b/ikuzo/rdf/index/path_query_syntax.md index 459aee74..6070e87c 100644 --- a/ikuzo/rdf/index/path_query_syntax.md +++ b/ikuzo/rdf/index/path_query_syntax.md @@ -44,6 +44,12 @@ Empty class brackets (`[]`) represent a wildcard for node traversal. For example ``` This indicates traversal via the `crm:P102_has_title` relationship to any node, regardless of its class. +Several classes, separated by `|` without spaces, mean any of them: +``` +[]schema:creator->[schema:Person|schema:Organization]schema:name +``` +This is the name of a creator that is a person or an organisation. + ### Traversal Arrows The `->` symbol indicates traversal between nodes: @@ -121,3 +127,21 @@ Example: 4. Only one value path can be specified. 5. The value path must come after any filter expressions. 6. Empty path strings are valid and will result in a nil PathQuery. + +## In the search index + +`fragments.ParseResourcePath` reads a resource path in this syntax and turns it into an +Elasticsearch query on the v2 index (`fragments.ResourcePath`). There every linked resource +is a nested `resources` element whose `context` records its route from the record's root: +one element per hop, with its `Level`, the predicate's `SearchLabel` and the `SubjectClass` +of the resource the hop starts from, which is what `[class]predicate` names. So any number +of hops can be queried, and several conditions can hold for the same linked resource: + +``` +[]schema:creator->[schema:Role]schema:creator->[schema:Person]schema:name = "Sphinx" +[]schema:creator->[schema:Role] with name "fabrikanten" and creator "Sphinx" +``` + +A path that ends with a predicate ends at a literal of the last resource; one that ends with +`[class]` ends at that resource, to test its class or its URI. Filters and value paths +(` | `) are not used there: the caller supplies the values. diff --git a/ikuzo/rdf/index/path_query_test.go b/ikuzo/rdf/index/path_query_test.go index 66c43009..036c8c08 100644 --- a/ikuzo/rdf/index/path_query_test.go +++ b/ikuzo/rdf/index/path_query_test.go @@ -535,3 +535,25 @@ func TestParseCsvPathMap(t *testing.T) { t.Errorf("golden file %s mismatch (-want +got):\n%s", "publisher", diff) } } + +// A class in a path may be several, separated by |: the resource has one of +// them. +func TestPathAlternativeClasses(t *testing.T) { + is := is.New(t) + + entries, err := ParsePath("[]schema:creator->[schema:Person|schema:Organization]schema:name", true) + is.NoErr(err) + is.Equal(len(entries), 2) + is.Equal(entries[1].Class, "https://schema.org/Person|https://schema.org/Organization") + is.Equal(entries[1].Classes(), []string{"https://schema.org/Person", "https://schema.org/Organization"}) + is.Equal(entries[0].Classes(), []string(nil)) // [] is any class + + org := &Resource{Types: []string{"https://schema.org/Organization"}} + place := &Resource{Types: []string{"https://schema.org/Place"}} + is.True(matchesClass(org, entries[1].Class)) + is.True(!matchesClass(place, entries[1].Class)) + is.True(matchesClass(place, entries[0].Class)) + + _, err = ParsePath("[schema:Person||schema:Organization]schema:name", true) + is.True(err != nil) // an empty alternative +}