diff --git a/config/config.go b/config/config.go index 302b3f3a..7f62324d 100644 --- a/config/config.go +++ b/config/config.go @@ -231,10 +231,10 @@ type OAIPMH struct { // WebResource holds all the configuration options for the WebResource endpoint type WebResource struct { - Enabled bool `json:"enabled"` // Make the webresource endpoint available - WebResourceDir string `json:"sourceDir"` // Target directory for the webresources - CacheResourceDir string `json:"cacheDir"` // cache directory for the webresources - enableSearch bool `json:"enableSearch"` // enable searching for images in ElasticSearch + Enabled bool `json:"enabled"` // Make the webresource endpoint available + WebResourceDir string `json:"sourceDir"` // Target directory for the webresources + CacheResourceDir string `json:"cacheDir"` // cache directory for the webresources + enableSearch bool // enable searching for images in ElasticSearch MediaManagerHost string `json:"mediaManagerHost"` // the domain to build the derivatives SmallDefault string `json:"smallDefault"` MediumDefault string `json:"mediumDefault"` @@ -405,7 +405,7 @@ func setDefaults() { // sitemap viper.SetDefault("SiteMap.Enabled", false) - // pid + // pid viper.SetDefault("PID.enabled", false) // ead diff --git a/config/config_suite_test.go b/config/config_suite_test.go index 4e3834e9..859a78b9 100644 --- a/config/config_suite_test.go +++ b/config/config_suite_test.go @@ -4,7 +4,7 @@ // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/hub3/ead/dao.go b/hub3/ead/dao.go index acc813ed..9f2af38a 100644 --- a/hub3/ead/dao.go +++ b/hub3/ead/dao.go @@ -150,13 +150,13 @@ func (c *DaoClient) PublishFindingAid(cfg *DaoConfig, excludeMetsFiles ...bool) } if !excludeFiles { - err = c.PublishFiles(cfg, &fa) + err = c.PublishFiles(cfg, fa) if err != nil { return err } } - fg, err := cfg.findingAidFragmentGraph(&fa) + fg, err := cfg.findingAidFragmentGraph(fa) if err != nil { return err } @@ -176,7 +176,7 @@ func (c *DaoClient) PublishFindingAid(cfg *DaoConfig, excludeMetsFiles ...bool) if !excludeFiles { cfg.ObjectCount = int(fa.GetFileCount()) - cfg.MimeTypes = getMimeTypes(&fa) + cfg.MimeTypes = getMimeTypes(fa) return c.dropOrphans(cfg) } @@ -497,16 +497,16 @@ func (cfg *DaoConfig) Mets() (*Cmets, error) { return readMETS(cfg.GetMetsFilePath()) } -func (cfg *DaoConfig) FindingAid(c *DaoClient) (eadpb.FindingAid, error) { +func (cfg *DaoConfig) FindingAid(c *DaoClient) (*eadpb.FindingAid, error) { if c.HttpFallback && !cfg.MetsFileExists() { if err := c.StoreMets(cfg); err != nil { - return eadpb.FindingAid{}, err + return nil, err } } mets, err := cfg.Mets() if err != nil { - return eadpb.FindingAid{}, err + return nil, err } return mets.newFindingAid(cfg) diff --git a/hub3/ead/eadpb/scan.go b/hub3/ead/eadpb/scan.go index 7463092e..34ab1c72 100644 --- a/hub3/ead/eadpb/scan.go +++ b/hub3/ead/eadpb/scan.go @@ -25,8 +25,8 @@ import ( ) // NewPager creates a new Pager with all navigation settings. -func NewPager(total int64, request *ViewRequest) (Pager, error) { - pager := Pager{ +func NewPager(total int64, request *ViewRequest) (*Pager, error) { + pager := &Pager{ HasNext: false, HasPrevious: false, TotalCount: int32(total), diff --git a/hub3/ead/eadpb/scan_test.go b/hub3/ead/eadpb/scan_test.go index 4d36f261..9a800ef4 100644 --- a/hub3/ead/eadpb/scan_test.go +++ b/hub3/ead/eadpb/scan_test.go @@ -35,13 +35,13 @@ func TestNewPager(t *testing.T) { tests := []struct { name string args args - want Pager + want *Pager wantErr bool }{ { "no results", args{total: 0, request: &ViewRequest{PageSize: int32(10), Page: int32(1)}}, - Pager{ + &Pager{ HasNext: false, HasPrevious: false, TotalCount: 0, @@ -59,7 +59,7 @@ func TestNewPager(t *testing.T) { { "1 page results", args{total: 3, request: &ViewRequest{PageSize: int32(10), Page: int32(1)}}, - Pager{ + &Pager{ HasNext: false, HasPrevious: false, TotalCount: 3, @@ -77,7 +77,7 @@ func TestNewPager(t *testing.T) { { "first page; 2 page results; 11 hits", args{total: 11, request: &ViewRequest{PageSize: int32(10), Page: int32(1)}}, - Pager{ + &Pager{ HasNext: true, HasPrevious: false, TotalCount: 11, @@ -95,7 +95,7 @@ func TestNewPager(t *testing.T) { { "second page; 2 page results; 11 hits", args{total: 11, request: &ViewRequest{PageSize: int32(10), Page: int32(2)}}, - Pager{ + &Pager{ HasNext: false, HasPrevious: true, TotalCount: 11, @@ -117,7 +117,7 @@ func TestNewPager(t *testing.T) { Page: int32(1), SortKey: 4, }}, - Pager{ + &Pager{ HasNext: false, HasPrevious: false, TotalCount: 10, @@ -139,7 +139,7 @@ func TestNewPager(t *testing.T) { Page: int32(1), Filename: "123.jpg", }}, - Pager{ + &Pager{ HasNext: false, HasPrevious: false, TotalCount: 10, @@ -161,7 +161,7 @@ func TestNewPager(t *testing.T) { Page: int32(5), Paging: true, }}, - Pager{ + &Pager{ HasNext: true, HasPrevious: true, TotalCount: 105, @@ -182,7 +182,7 @@ func TestNewPager(t *testing.T) { PageSize: int32(1), Page: int32(5), }}, - Pager{ + &Pager{ HasNext: true, HasPrevious: true, TotalCount: 15, @@ -224,7 +224,7 @@ func TestSetPage(t *testing.T) { tests := []struct { name string args args - want Pager + want *Pager wantErr bool }{ { @@ -234,7 +234,7 @@ func TestSetPage(t *testing.T) { request: &ViewRequest{PageSize: int32(10), Page: int32(1)}, sortKey: int32(5), }, - Pager{ + &Pager{ HasNext: true, HasPrevious: false, TotalCount: 17, @@ -256,7 +256,7 @@ func TestSetPage(t *testing.T) { request: &ViewRequest{PageSize: int32(10), Page: int32(1)}, sortKey: int32(15), }, - Pager{ + &Pager{ HasNext: false, HasPrevious: true, TotalCount: 17, diff --git a/hub3/ead/mets.go b/hub3/ead/mets.go index 9c17fba7..34547b78 100644 --- a/hub3/ead/mets.go +++ b/hub3/ead/mets.go @@ -155,8 +155,8 @@ func updateFileInfo(files map[string]*eadpb.File, fg []*CfileGrp, fa *eadpb.Find return nil } -func (mets *Cmets) newFindingAid(cfg *DaoConfig) (eadpb.FindingAid, error) { - fa := eadpb.FindingAid{ +func (mets *Cmets) newFindingAid(cfg *DaoConfig) (*eadpb.FindingAid, error) { + fa := &eadpb.FindingAid{ ArchiveID: cfg.ArchiveID, InventoryID: cfg.InventoryID, InventoryPath: cfg.InventoryPath, @@ -178,7 +178,7 @@ func (mets *Cmets) newFindingAid(cfg *DaoConfig) (eadpb.FindingAid, error) { return fa, err } - err = updateFileInfo(files, mets.CfileSec.CfileGrp, &fa) + err = updateFileInfo(files, mets.CfileSec.CfileGrp, fa) if err != nil { return fa, err } diff --git a/hub3/ead/mets_test.go b/hub3/ead/mets_test.go index 74f5ad99..aee68ee6 100644 --- a/hub3/ead/mets_test.go +++ b/hub3/ead/mets_test.go @@ -66,12 +66,12 @@ func TestFindingAidMimeTypes(t *testing.T) { t.Errorf("not all mimetypes counted, got %d: want %d", count, 140) } - if len(getMimeTypes(&findingAid)) != 1 { - t.Errorf("wrong count for mime-types, got %d: want %d", len(getMimeTypes(&findingAid)), 1) + if len(getMimeTypes(findingAid)) != 1 { + t.Errorf("wrong count for mime-types, got %d: want %d", len(getMimeTypes(findingAid)), 1) } - if getMimeTypes(&findingAid)[0] != "image/jpeg" { - t.Errorf("not the right mime-type array, got %#v", getMimeTypes(&findingAid)) + if getMimeTypes(findingAid)[0] != "image/jpeg" { + t.Errorf("not the right mime-type array, got %#v", getMimeTypes(findingAid)) } } diff --git a/hub3/ead/number_gen.go b/hub3/ead/number_gen.go index 2e24f387..f79b9de5 100644 --- a/hub3/ead/number_gen.go +++ b/hub3/ead/number_gen.go @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build ignore // +build ignore package main diff --git a/hub3/fragments/api.go b/hub3/fragments/api.go index dd95ae67..573b78d0 100644 --- a/hub3/fragments/api.go +++ b/hub3/fragments/api.go @@ -1346,13 +1346,13 @@ func (sr *SearchRequest) executeBatchAggregations(ec *elastic.Client, fub *Facet batchFieldNames := make([]string, 0, len(facetBatch)) for _, facetField := range facetBatch { // Create a size-limited copy of the facet field - facetCopy := *facetField + facetCopy := proto.Clone(facetField).(*FacetField) if sr.FacetLimit != 0 { facetCopy.Size = sr.FacetLimit } // Create aggregation for this specific field - agg, err := sr.CreateAggregationBySearchLabel(resourcesEntries, &facetCopy, fub) + agg, err := sr.CreateAggregationBySearchLabel(resourcesEntries, facetCopy, fub) if err != nil { return nil, fmt.Errorf("failed to create aggregation for %s: %w", facetField.GetField(), err) } @@ -1478,9 +1478,9 @@ func (sr *SearchRequest) CreateAggregationBySearchLabel(path string, facet *Face // TERMS falls through to the default case, which builds the // composite value listing we need for sortValue ordering. if facet.GetType() == FacetType_FIELDS && facet.GetByName() { - facetCopy := *facet + facetCopy := proto.Clone(facet).(*FacetField) facetCopy.Type = FacetType_TERMS - facet = &facetCopy + facet = facetCopy } return CreateAggregationBySearchLabel(path, facet, sr.FacetAndBoolType, fub) diff --git a/hub3/fragments/example_semantic_test.go b/hub3/fragments/example_semantic_test.go index b5e30e3b..68e996e7 100644 --- a/hub3/fragments/example_semantic_test.go +++ b/hub3/fragments/example_semantic_test.go @@ -167,4 +167,4 @@ func TestSemanticFormatExample(t *testing.T) { require.Equal(t, "fr", frDesc.Language) fmt.Println("\nExample semantic format test completed successfully!") -} \ No newline at end of file +} diff --git a/hub3/fragments/fragments.go b/hub3/fragments/fragments.go index eeee3091..5f0b3230 100644 --- a/hub3/fragments/fragments.go +++ b/hub3/fragments/fragments.go @@ -226,9 +226,8 @@ func (fr *FragmentRequest) Find(ctx context.Context, client *elastic.Client) ([] seen := map[string]bool{} - var frtyp Fragment - for idx, item := range res.Each(reflect.TypeOf(frtyp)) { - frag := item.(Fragment) + for idx, item := range res.Each(reflect.TypeOf(&Fragment{})) { + frag := item.(*Fragment) // if subject is the prefix of the named graph then return the whole graph if idx == 0 && len(fr.Subject) != 0 { @@ -243,7 +242,7 @@ func (fr *FragmentRequest) Find(ctx context.Context, client *elastic.Client) ([] _, ok := seen[frag.Triple] if !ok { - fragments = append(fragments, &frag) + fragments = append(fragments, frag) seen[frag.Triple] = true } } @@ -271,7 +270,7 @@ func (f *Fragment) ID() string { // CreateBulkIndexRequest converts the fragment into a request that can be // submitted to the ElasticSearch BulkIndexService -func (f Fragment) IndexMessage() (*domainpb.IndexMessage, error) { +func (f *Fragment) IndexMessage() (*domainpb.IndexMessage, error) { b, err := json.Marshal(f) if err != nil { return nil, err @@ -288,7 +287,7 @@ func (f Fragment) IndexMessage() (*domainpb.IndexMessage, error) { } // AddTo adds the BulkableRequest to the Storage interface where it is flushed periodically. -func (f Fragment) AddTo(bi BulkIndex) error { +func (f *Fragment) AddTo(bi BulkIndex) error { m, err := f.IndexMessage() if err != nil { return err diff --git a/hub3/fragments/graph.go b/hub3/fragments/graph.go index 29d33b8a..cc1a9348 100644 --- a/hub3/fragments/graph.go +++ b/hub3/fragments/graph.go @@ -27,7 +27,7 @@ type FragmentGraph struct { } type RelatedItems struct { - Items []*ItemV1 `json:"item,omitempty"` + Items []*ItemV1 `json:"item,omitempty"` SemanticItems []*FragmentGraph `json:"items,omitempty"` } diff --git a/hub3/fragments/searchfields.go b/hub3/fragments/searchfields.go index 90f5b0e3..e4e5b362 100644 --- a/hub3/fragments/searchfields.go +++ b/hub3/fragments/searchfields.go @@ -16,7 +16,7 @@ type FieldInfo struct { func detectSearchFields(query string) FieldInfo { // Custom parsing implementation for field detection // This is more robust than using a single regex pattern - + // Handle special cases first if query == "" { return FieldInfo{ @@ -25,19 +25,19 @@ func detectSearchFields(query string) FieldInfo { Count: 0, } } - + // Check for valid field pattern: field:value // A valid field name must: // 1. Start with a letter or underscore // 2. Contain only letters, numbers, dots, or underscores // 3. Be followed by a colon and not at the end of a string // 4. Not be preceded by another alphanumeric, dot or underscore - + // Basic check for valid field patterns validFieldRegex := regexp.MustCompile(`(^|[^a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_.]*):\S`) - + matches := validFieldRegex.FindAllStringSubmatch(query, -1) - + if len(matches) == 0 { return FieldInfo{ HasFields: false, @@ -45,7 +45,7 @@ func detectSearchFields(query string) FieldInfo { Count: 0, } } - + // Extract unique field names fieldSet := make(map[string]bool) for _, match := range matches { @@ -54,12 +54,12 @@ func detectSearchFields(query string) FieldInfo { fieldSet[fieldName] = true } } - + // Handle specific edge cases that should not match // Check for "text with colon: but no field" invalidColonRegex := regexp.MustCompile(`\s\w+:(\s|$)`) invalidMatches := invalidColonRegex.FindAllString(query, -1) - + // If we only have invalid matches (like "text: " or "colon: "), return no fields if len(invalidMatches) > 0 && len(fieldSet) == 1 { for field := range fieldSet { @@ -76,13 +76,13 @@ func detectSearchFields(query string) FieldInfo { } } } - + // Convert to slice fields := make([]string, 0, len(fieldSet)) for field := range fieldSet { fields = append(fields, field) } - + return FieldInfo{ HasFields: true, Fields: fields, diff --git a/hub3/fragments/semantic.go b/hub3/fragments/semantic.go index 013f89db..066fc08d 100644 --- a/hub3/fragments/semantic.go +++ b/hub3/fragments/semantic.go @@ -273,9 +273,9 @@ func (sr *SemanticResource) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &m); err != nil { return err } - + sr.Fields = make(map[string]SemanticValue) - + // Process each field for k, v := range m { switch k { @@ -308,7 +308,7 @@ func (sr *SemanticResource) UnmarshalJSON(data []byte) error { sr.Fields[k] = val } } - + return nil } @@ -350,7 +350,7 @@ func (sa *SemanticArray) UnmarshalJSON(data []byte) error { } return nil } - + // Not an array, treat as single value val, err := unmarshalSemanticValue(data) if err != nil { @@ -393,7 +393,7 @@ func unmarshalSemanticValue(data []byte) (SemanticValue, error) { } return &tl, nil } - + // Check for @id or @type (resource) if _, hasID := m["@id"]; hasID { var r SemanticResource @@ -409,7 +409,7 @@ func unmarshalSemanticValue(data []byte) (SemanticValue, error) { } return &r, nil } - + // Check if it's a language map (all keys are language codes) isLangMap := true for k := range m { @@ -425,7 +425,7 @@ func unmarshalSemanticValue(data []byte) (SemanticValue, error) { } return &lm, nil } - + // It's a resource without @id or @type var r SemanticResource if err := json.Unmarshal(data, &r); err != nil { @@ -433,7 +433,7 @@ func unmarshalSemanticValue(data []byte) (SemanticValue, error) { } return &r, nil } - + // Try array var arr []json.RawMessage if err := json.Unmarshal(data, &arr); err == nil { @@ -443,7 +443,7 @@ func unmarshalSemanticValue(data []byte) (SemanticValue, error) { } return &sa, nil } - + // Must be a simple literal var sl SemanticLiteral if err := json.Unmarshal(data, &sl.Value); err != nil { @@ -458,12 +458,12 @@ func isLanguageCode(code string) bool { if len(code) < 2 || len(code) > 7 { return false } - + parts := strings.Split(code, "-") if len(parts) > 2 { return false } - + // Check first part (language) lang := parts[0] if len(lang) < 2 || len(lang) > 3 { @@ -474,7 +474,7 @@ func isLanguageCode(code string) bool { return false } } - + // Check second part if exists (region) if len(parts) == 2 { region := parts[1] @@ -487,7 +487,7 @@ func isLanguageCode(code string) bool { } } } - + return true } @@ -516,20 +516,20 @@ func newSemanticLiteralValue(entry *ResourceEntry) SemanticValue { if entry.Language == "" && entry.DataType == "" { return &SemanticLiteral{Value: entry.Value} } - + // Typed or language literal lit := &SemanticTypedLiteral{Value: entry.Value} - + if entry.Language != "" { lit.Language = entry.Language } - + if entry.DataType != "" { lit.Type = entry.DataType // Convert value based on datatype lit.Value = convertTypedValue(entry.Value, entry.DataType) } - + return lit } @@ -598,47 +598,47 @@ func (fg *FragmentGraph) GenerateSemantic() *SemanticView { for _, r := range fg.Resources { rm.resources[r.ID] = r } - + // Find main resource (usually the first one or the one matching EntryURI) mainResource := fg.findMainResource() if mainResource != nil { sv.ID = mainResource.ID sv.Type = mainResource.Types - + // Group entries by SearchLabel (predicate) with order preservation predicateMap := make(map[string][]orderedEntry) - + for _, entry := range mainResource.Entries { // Skip entries without SearchLabel if entry.SearchLabel == "" { continue } - + // Skip rdf:type as it's already in @type if entry.Predicate == RDFType { continue } - + value := NewSemanticValue(entry, rm) predicateMap[entry.SearchLabel] = append( predicateMap[entry.SearchLabel], orderedEntry{order: entry.Order, value: value}, ) } - + // Convert to fields with proper typing and order for predicate, orderedValues := range predicateMap { // Sort by order field sort.Slice(orderedValues, func(i, j int) bool { return orderedValues[i].order < orderedValues[j].order }) - + // Extract values in order values := make([]SemanticValue, len(orderedValues)) for i, ov := range orderedValues { values[i] = ov.value } - + if len(values) == 1 { sv.Fields[predicate] = values[0] } else if len(values) > 1 { @@ -647,7 +647,7 @@ func (fg *FragmentGraph) GenerateSemantic() *SemanticView { } } } - + return sv } @@ -732,7 +732,7 @@ func (fr *FragmentResource) toSemanticResourceWithCycleDetection(rm *ResourceMap func (fg *FragmentGraph) GetUniqueNamespaces() map[string]string { // Use a map to track unique namespace URIs namespaceURIs := make(map[string]bool) - + // Collect all predicates and types for _, resource := range fg.Resources { // Add types (RDF classes) @@ -742,14 +742,14 @@ func (fg *FragmentGraph) GetUniqueNamespaces() map[string]string { namespaceURIs[base] = true } } - + // Add predicates from entries for _, entry := range resource.Entries { base, _ := domain.SplitURI(entry.Predicate) if base != "" { namespaceURIs[base] = true } - + // Also check DataType for typed literals if entry.DataType != "" { base, _ := domain.SplitURI(entry.DataType) @@ -759,10 +759,10 @@ func (fg *FragmentGraph) GetUniqueNamespaces() map[string]string { } } } - + // Now resolve the URIs to prefixes using the namespace manager namespaces := make(map[string]string) - + if rdf.DefaultNamespaceManager != nil { for uri := range namespaceURIs { // Try to get the namespace with this base URI @@ -771,7 +771,7 @@ func (fg *FragmentGraph) GetUniqueNamespaces() map[string]string { } } } - + return namespaces } @@ -784,9 +784,9 @@ func (fg *FragmentGraph) buildSemanticContext() interface{} { if len(fg.Resources) > 0 && len(fg.Resources[0].Types) > 0 { for _, t := range fg.Resources[0].Types { if strings.Contains(t, "europeana.eu/schemas/edm") || - strings.Contains(t, "ProvidedCHO") || - strings.Contains(t, "Aggregation") || - strings.Contains(t, "WebResource") { + strings.Contains(t, "ProvidedCHO") || + strings.Contains(t, "Aggregation") || + strings.Contains(t, "WebResource") { isEDM = true break } @@ -828,7 +828,7 @@ func (fg *FragmentGraph) findMainResource() *FragmentResource { if len(fg.Resources) == 0 { return nil } - + // Try to find resource matching EntryURI if fg.Meta != nil && fg.Meta.EntryURI != "" { for _, r := range fg.Resources { @@ -837,7 +837,7 @@ func (fg *FragmentGraph) findMainResource() *FragmentResource { } } } - + // Fallback to first resource return fg.Resources[0] -} \ No newline at end of file +} diff --git a/hub3/fragments/semantic_test.go b/hub3/fragments/semantic_test.go index f9c945d2..7956b03e 100644 --- a/hub3/fragments/semantic_test.go +++ b/hub3/fragments/semantic_test.go @@ -12,74 +12,74 @@ import ( func TestSemanticValueTypes(t *testing.T) { t.Run("SemanticLiteral", func(t *testing.T) { lit := &SemanticLiteral{Value: "test value"} - + assert.False(t, lit.IsResource()) assert.Equal(t, "test value", lit.GetValue()) - + // Test JSON marshaling data, err := json.Marshal(lit) require.NoError(t, err) assert.Equal(t, `"test value"`, string(data)) - + // Test JSON unmarshaling var unmarshaled SemanticLiteral err = json.Unmarshal(data, &unmarshaled) require.NoError(t, err) assert.Equal(t, "test value", unmarshaled.Value) }) - + t.Run("SemanticTypedLiteral", func(t *testing.T) { // Test with language langLit := &SemanticTypedLiteral{ Value: "Nederlandse tekst", Language: "nl", } - + assert.False(t, langLit.IsResource()) assert.Equal(t, "Nederlandse tekst", langLit.GetValue()) - + data, err := json.Marshal(langLit) require.NoError(t, err) - + var result map[string]interface{} err = json.Unmarshal(data, &result) require.NoError(t, err) assert.Equal(t, "Nederlandse tekst", result["@value"]) assert.Equal(t, "nl", result["@language"]) - + // Test with datatype typedLit := &SemanticTypedLiteral{ Value: "2024-01-15", Type: "xsd:date", } - + data, err = json.Marshal(typedLit) require.NoError(t, err) - + err = json.Unmarshal(data, &result) require.NoError(t, err) assert.Equal(t, "2024-01-15", result["@value"]) assert.Equal(t, "xsd:date", result["@type"]) }) - + t.Run("SemanticLanguageMap", func(t *testing.T) { langMap := SemanticLanguageMap{ "nl": "Nederlandse naam", "en": "English name", } - + assert.False(t, langMap.IsResource()) - + data, err := json.Marshal(langMap) require.NoError(t, err) - + var result map[string]string err = json.Unmarshal(data, &result) require.NoError(t, err) assert.Equal(t, "Nederlandse naam", result["nl"]) assert.Equal(t, "English name", result["en"]) }) - + t.Run("SemanticResource", func(t *testing.T) { resource := &SemanticResource{ ID: "resource/person/123", @@ -88,13 +88,13 @@ func TestSemanticValueTypes(t *testing.T) { "skos:prefLabel": &SemanticLiteral{Value: "John Doe"}, }, } - + assert.True(t, resource.IsResource()) assert.Equal(t, resource, resource.GetValue()) - + data, err := json.Marshal(resource) require.NoError(t, err) - + var result map[string]interface{} err = json.Unmarshal(data, &result) require.NoError(t, err) @@ -102,14 +102,14 @@ func TestSemanticValueTypes(t *testing.T) { assert.Equal(t, "edm:Agent", result["@type"]) assert.Equal(t, "John Doe", result["skos:prefLabel"]) }) - + t.Run("SemanticArray", func(t *testing.T) { // Test single value - should unwrap single := SemanticArray{&SemanticLiteral{Value: "single"}} data, err := json.Marshal(single) require.NoError(t, err) assert.Equal(t, `"single"`, string(data)) - + // Test multiple values - should keep as array multiple := SemanticArray{ &SemanticLiteral{Value: "first"}, @@ -137,7 +137,7 @@ func TestLanguageCodeValidation(t *testing.T) { {"123", false}, {"EN", false}, // Must be lowercase } - + for _, tt := range tests { t.Run(tt.code, func(t *testing.T) { assert.Equal(t, tt.valid, isLanguageCode(tt.code)) @@ -161,7 +161,7 @@ func TestConvertTypedValue(t *testing.T) { {"unknown type", "value", "custom:type", "value"}, {"invalid integer", "not-a-number", "xsd:integer", "not-a-number"}, } - + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := convertTypedValue(tt.value, tt.datatype) @@ -176,53 +176,53 @@ func TestNewSemanticValue(t *testing.T) { EntryType: literal, Value: "test value", } - + value := NewSemanticValue(entry, nil) lit, ok := value.(*SemanticLiteral) require.True(t, ok) assert.Equal(t, "test value", lit.Value) }) - + t.Run("creates typed literal with language", func(t *testing.T) { entry := &ResourceEntry{ EntryType: literal, Value: "Nederlandse tekst", Language: "nl", } - + value := NewSemanticValue(entry, nil) typedLit, ok := value.(*SemanticTypedLiteral) require.True(t, ok) assert.Equal(t, "Nederlandse tekst", typedLit.Value) assert.Equal(t, "nl", typedLit.Language) }) - + t.Run("creates typed literal with datatype", func(t *testing.T) { entry := &ResourceEntry{ EntryType: literal, Value: "42", DataType: "xsd:integer", } - + value := NewSemanticValue(entry, nil) typedLit, ok := value.(*SemanticTypedLiteral) require.True(t, ok) assert.Equal(t, 42, typedLit.Value) // Should be converted to int assert.Equal(t, "xsd:integer", typedLit.Type) }) - + t.Run("creates resource for resource entry", func(t *testing.T) { entry := &ResourceEntry{ EntryType: resourceType, ID: "resource/123", } - + value := NewSemanticValue(entry, nil) resource, ok := value.(*SemanticResource) require.True(t, ok) assert.Equal(t, "resource/123", resource.ID) }) - + t.Run("creates resource from inline", func(t *testing.T) { inline := &FragmentResource{ ID: "inline/resource", @@ -237,23 +237,23 @@ func TestNewSemanticValue(t *testing.T) { }, }, } - + entry := &ResourceEntry{ EntryType: resourceType, ID: "resource/123", Inline: inline, } - + rm := &ResourceMap{ resources: make(map[string]*FragmentResource), } - + value := NewSemanticValue(entry, rm) resource, ok := value.(*SemanticResource) require.True(t, ok) assert.Equal(t, "inline/resource", resource.ID) assert.Equal(t, []string{"edm:Agent"}, resource.Type) - + // Check that the inline resource has fields prefLabel, exists := resource.Fields["skos:prefLabel"] require.True(t, exists) @@ -292,37 +292,37 @@ func TestSemanticViewMarshaling(t *testing.T) { }, }, } - + data, err := json.Marshal(sv) require.NoError(t, err) - + var result map[string]interface{} err = json.Unmarshal(data, &result) require.NoError(t, err) - + // Check @context context, ok := result["@context"].(map[string]interface{}) require.True(t, ok) assert.Equal(t, "http://purl.org/dc/elements/1.1/", context["dc"]) - + // Check @id and @type assert.Equal(t, "resource/item/123", result["@id"]) assert.Equal(t, "edm:ProvidedCHO", result["@type"]) - + // Check fields are at root level title, ok := result["dc:title"].(map[string]interface{}) require.True(t, ok) assert.Equal(t, "Test Title", title["@value"]) assert.Equal(t, "en", title["@language"]) - + assert.Equal(t, "ID123", result["dc:identifier"]) - + // Check nested resource person, ok := result["edm:isRepresentationOf"].(map[string]interface{}) require.True(t, ok) assert.Equal(t, "resource/person/456", person["@id"]) assert.Equal(t, "edm:Agent", person["@type"]) - + prefLabel, ok := person["skos:prefLabel"].(map[string]interface{}) require.True(t, ok) assert.Equal(t, "Nederlandse naam", prefLabel["nl"]) @@ -333,46 +333,46 @@ func TestFragmentGraphGenerateSemantic(t *testing.T) { // Load test data from file data, err := os.ReadFile("testdata/nk_fg_grouped.json") require.NoError(t, err) - + var fg FragmentGraph err = json.Unmarshal(data, &fg) require.NoError(t, err) - + // Generate semantic view sv := fg.GenerateSemantic() require.NotNil(t, sv) - + // Check basic structure assert.Equal(t, "https://wo2.collectienederland.nl/id/nk/NK1145", sv.ID) assert.Contains(t, sv.Type, "https://wo2.collectienederland.nl/nk/terms/NKRecord") - + // Check context has namespaces assert.NotEmpty(t, sv.Context) - + // Check that fields are present assert.NotEmpty(t, sv.Fields) - + // Check specific field (thumbnail) thumbnail, exists := sv.Fields["nk_thumbnail"] require.True(t, exists) lit, ok := thumbnail.(*SemanticLiteral) require.True(t, ok) assert.Contains(t, lit.Value, "https://media.delving.org") - + // Check that order is preserved by checking if timeline resource exists timeline, exists := sv.Fields["nk_timeline"] require.True(t, exists, "nk_timeline field should exist") - + // The timeline field should be an array since there are multiple timeline entries arr, ok := timeline.(*SemanticArray) require.True(t, ok, "timeline should be a *SemanticArray since there are multiple entries") require.NotEmpty(t, *arr, "timeline array should not be empty") - + // Check the first timeline resource firstTimeline, ok := (*arr)[0].(*SemanticResource) require.True(t, ok, "first timeline entry should be a *SemanticResource") assert.Equal(t, "https://wo2.collectienederland.nl/id/timeline/NK1145/1960-01-01", firstTimeline.ID) - + // Verify we have all 7 timeline entries assert.Len(t, *arr, 7, "should have 7 timeline entries") } @@ -405,16 +405,16 @@ func TestOrderPreservation(t *testing.T) { }, }, } - + sr := fr.ToSemanticResource(nil) - + // Check that all fields are present assert.Len(t, sr.Fields, 3) - + // Marshal to JSON to check order _, err := json.Marshal(sr) require.NoError(t, err) - + // The order in the map doesn't matter for JSON, but when we have multiple // values for the same field, they should be ordered fr2 := &FragmentResource{ @@ -444,15 +444,15 @@ func TestOrderPreservation(t *testing.T) { }, }, } - + sr2 := fr2.ToSemanticResource(nil) multiField := sr2.Fields["field:multi"] require.NotNil(t, multiField) - + arr, ok := multiField.(*SemanticArray) require.True(t, ok) require.Len(t, *arr, 3) - + // Check order assert.Equal(t, "first", (*arr)[0].(*SemanticLiteral).Value) assert.Equal(t, "second", (*arr)[1].(*SemanticLiteral).Value) @@ -477,11 +477,11 @@ func TestGetUniqueNamespaces(t *testing.T) { }, }, } - + // Note: This test will only work if the namespace manager is properly initialized // In a real test environment, you would need to set up the namespace manager first namespaces := fg.GetUniqueNamespaces() - + // The function should extract unique namespace URIs // Since we don't have the namespace manager set up in tests, // we just check that the function doesn't panic @@ -977,4 +977,4 @@ func TestCycleDetection(t *testing.T) { _, hasRefType := expandedMap["hub3:referenceType"] assert.False(t, hasRefType, "fully expanded resource should not have hub3:referenceType") }) -} \ No newline at end of file +} diff --git a/hub3/fragments/sparql_test.go b/hub3/fragments/sparql_test.go index 6e5f5b26..c2de41eb 100644 --- a/hub3/fragments/sparql_test.go +++ b/hub3/fragments/sparql_test.go @@ -4,7 +4,7 @@ // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/hub3/models/dataset_drop_records_test.go b/hub3/models/dataset_drop_records_test.go index 9896f844..4d6eeaaa 100644 --- a/hub3/models/dataset_drop_records_test.go +++ b/hub3/models/dataset_drop_records_test.go @@ -240,8 +240,8 @@ func TestDeleteIndexRecordsByHubIDsUsesLegacyFieldsForV1(t *testing.T) { []string{"org1_ds1_a"}, ) is.NoErr(err) - is.Equal(count, 2) // one per index - is.Equal(len(captured), 2) // both v1 and v2 indices hit + is.Equal(count, 2) // one per index + is.Equal(len(captured), 2) // both v1 and v2 indices hit v1Index := c.Config.ElasticSearch.GetV1IndexName("org1") v2Index := c.Config.ElasticSearch.GetIndexName("org1") diff --git a/hub3/models/indexing_batch.go b/hub3/models/indexing_batch.go index dfbb9f03..00890da3 100644 --- a/hub3/models/indexing_batch.go +++ b/hub3/models/indexing_batch.go @@ -321,11 +321,12 @@ func CleanupOldBatches(maxAge time.Duration) (int, error) { } deleted := 0 - for _, batch := range batches { + for i := range batches { + batch := &batches[i] // Only delete completed/failed batches older than cutoff if (batch.Status == BatchStatusCompleted || batch.Status == BatchStatusFailed) && batch.CompletedAt.Before(cutoff) { - if err := ORM().DeleteStruct(&batch); err != nil { + if err := ORM().DeleteStruct(batch); err != nil { log.Warn().Err(err).Str("batchID", batch.ID).Msg("failed to delete old batch") continue } diff --git a/hub3/server/http/handlers/morelikethis.go b/hub3/server/http/handlers/morelikethis.go index c7429449..7df0815d 100644 --- a/hub3/server/http/handlers/morelikethis.go +++ b/hub3/server/http/handlers/morelikethis.go @@ -49,9 +49,9 @@ func MoreLikeThisSearch( marshalStringSlice(searchLabelFields), c.Config.ElasticSearch.GetIndexName(orgID), hubID) - + var queryJSON string - + // Process filters if we have any if len(filters) > 0 { // Process filters and add "fields." prefix if needed @@ -67,7 +67,7 @@ func MoreLikeThisSearch( processedFilters[i] = filter } } - + // Create filter terms JSON var filterTerms []string for _, filter := range processedFilters { @@ -76,19 +76,19 @@ func MoreLikeThisSearch( if len(parts) == 2 { field := parts[0] value := parts[1] - + // Escape any quotes in the value value = escapeJSON(value) - + // Create the term filter JSON filterTerm := fmt.Sprintf(`{"term":{"%s":"%s"}}`, field, value) filterTerms = append(filterTerms, filterTerm) } } - + // Join filter terms with commas filtersJSON := strings.Join(filterTerms, ",") - + // Build the combined bool query with must (more_like_this) and should (OR) for filters queryJSON = fmt.Sprintf(`{ "query": { @@ -111,7 +111,7 @@ func MoreLikeThisSearch( "size": %d }`, mltQuery, size) } - + rawQuery := queryJSON ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -161,4 +161,4 @@ func marshalStringSlice(slice []string) string { return "[]" } return string(bytes) -} \ No newline at end of file +} diff --git a/ikuzo/domain/semantic/collection.go b/ikuzo/domain/semantic/collection.go index 3e92da6f..b4f540c9 100644 --- a/ikuzo/domain/semantic/collection.go +++ b/ikuzo/domain/semantic/collection.go @@ -14,8 +14,8 @@ type Collection struct { GeoData *GeoFeatureCollection `json:"hub3:geoData,omitempty"` GeoClusters []GeoCluster `json:"hub3:geoClusters,omitempty"` SearchContext *SearchContext `json:"hub3:searchContext,omitempty"` - QueryContext *QueryContextRef `json:"hub3:queryContext,omitempty"` - Timing *Timing `json:"hub3:timing,omitempty"` + QueryContext *QueryContextRef `json:"hub3:queryContext,omitempty"` + Timing *Timing `json:"hub3:timing,omitempty"` // Debug contains diagnostic information when debug mode is enabled. Debug map[string]any `json:"hub3:debug,omitempty"` } @@ -42,15 +42,15 @@ type Timing struct { // Facet represents a facet aggregation result. type Facet struct { - TypeValue string `json:"@type,omitempty"` - Field string `json:"field"` - Label string `json:"label"` - PropertyURI string `json:"propertyURI,omitempty"` - FacetType string `json:"facetType"` // enum, range, date, boolean - TotalValues int64 `json:"totalValues,omitempty"` - Values []FacetValue `json:"values"` - Next string `json:"next,omitempty"` // URL for more values - NextCursor string `json:"hub3:nextCursor,omitempty"` // Opaque cursor for next page of facet values + TypeValue string `json:"@type,omitempty"` + Field string `json:"field"` + Label string `json:"label"` + PropertyURI string `json:"propertyURI,omitempty"` + FacetType string `json:"facetType"` // enum, range, date, boolean + TotalValues int64 `json:"totalValues,omitempty"` + Values []FacetValue `json:"values"` + Next string `json:"next,omitempty"` // URL for more values + NextCursor string `json:"hub3:nextCursor,omitempty"` // Opaque cursor for next page of facet values } // Type returns the @type for JSON-LD. @@ -63,15 +63,15 @@ func (f *Facet) Type() string { // FacetValue represents a single value in a facet. type FacetValue struct { - TypeValue string `json:"@type,omitempty"` - Value string `json:"value"` - Label string `json:"label,omitempty"` - Count int64 `json:"count"` - Selected bool `json:"selected"` - Filter string `json:"filter,omitempty"` // Ready-to-use filter string - ApplyURL string `json:"applyURL,omitempty"` - RemoveURL string `json:"removeURL,omitempty"` - Geometry map[string]interface{} `json:"geometry,omitempty"` // GeoJSON for region facets + TypeValue string `json:"@type,omitempty"` + Value string `json:"value"` + Label string `json:"label,omitempty"` + Count int64 `json:"count"` + Selected bool `json:"selected"` + Filter string `json:"filter,omitempty"` // Ready-to-use filter string + ApplyURL string `json:"applyURL,omitempty"` + RemoveURL string `json:"removeURL,omitempty"` + Geometry map[string]interface{} `json:"geometry,omitempty"` // GeoJSON for region facets } // Type returns the @type for JSON-LD. @@ -114,10 +114,10 @@ func (bli *BreadcrumbListItem) Type() string { // GeoFeatureCollection represents a GeoJSON FeatureCollection for map display. type GeoFeatureCollection struct { - TypeValue string `json:"@type,omitempty"` - Type string `json:"type"` // "FeatureCollection" - Features []GeoFeature `json:"features"` - BBox []float64 `json:"bbox,omitempty"` // [west, south, east, north] + TypeValue string `json:"@type,omitempty"` + Type string `json:"type"` // "FeatureCollection" + Features []GeoFeature `json:"features"` + BBox []float64 `json:"bbox,omitempty"` // [west, south, east, north] } // GeoFeature represents a single GeoJSON feature. diff --git a/ikuzo/domain/semantic/config.go b/ikuzo/domain/semantic/config.go index 65affdc1..3151faf0 100644 --- a/ikuzo/domain/semantic/config.go +++ b/ikuzo/domain/semantic/config.go @@ -13,10 +13,10 @@ type FilterConfig struct { Label string `json:"label"` Description string `json:"description"` AllowedOperators []Operator `json:"allowedOperators"` - AllowedInQuery bool `json:"allowedInQuery"` // Can be used in GET requests - AllowedInPost bool `json:"allowedInPost"` // Can be used in POST requests - ValueType string `json:"valueType"` // string, integer, float, boolean, date, uri - MultiValue bool `json:"multiValue"` // Whether multiple values are allowed + AllowedInQuery bool `json:"allowedInQuery"` // Can be used in GET requests + AllowedInPost bool `json:"allowedInPost"` // Can be used in POST requests + ValueType string `json:"valueType"` // string, integer, float, boolean, date, uri + MultiValue bool `json:"multiValue"` // Whether multiple values are allowed ValidationRegex string `json:"validationRegex,omitempty"` Examples []string `json:"examples,omitempty"` } @@ -100,20 +100,20 @@ func (fc *FilterConfig) Validate(filter Filter) error { // FacetConfig defines the configuration for a facet field. type FacetConfig struct { - Field string `json:"field"` - PropertyURI string `json:"propertyURI"` - Label string `json:"label"` - Description string `json:"description"` - FacetType string `json:"facetType"` // enum, range, date, boolean - Size int `json:"size"` // Number of values to return - MinDocCount int64 `json:"minDocCount"` - SortBy string `json:"sortBy"` // count, term, index - SortOrder string `json:"sortOrder"` // asc, desc - Missing bool `json:"missing"` // Include missing values - Ranges []FacetRange `json:"ranges,omitempty"` - DateIntervals []DateInterval `json:"dateIntervals,omitempty"` - URLTemplate string `json:"urlTemplate,omitempty"` // Template for facet URLs - Metadata map[string]any `json:"metadata,omitempty"` // Additional metadata + Field string `json:"field"` + PropertyURI string `json:"propertyURI"` + Label string `json:"label"` + Description string `json:"description"` + FacetType string `json:"facetType"` // enum, range, date, boolean + Size int `json:"size"` // Number of values to return + MinDocCount int64 `json:"minDocCount"` + SortBy string `json:"sortBy"` // count, term, index + SortOrder string `json:"sortOrder"` // asc, desc + Missing bool `json:"missing"` // Include missing values + Ranges []FacetRange `json:"ranges,omitempty"` + DateIntervals []DateInterval `json:"dateIntervals,omitempty"` + URLTemplate string `json:"urlTemplate,omitempty"` // Template for facet URLs + Metadata map[string]any `json:"metadata,omitempty"` // Additional metadata } // FacetRange defines a range for range facets. @@ -200,17 +200,17 @@ func (fc *FacetConfig) WithMetadata(key string, value any) *FacetConfig { // ResourceConfig defines the complete search configuration for a resource type. // This includes all filterable fields, facets, and resource-specific settings. type ResourceConfig struct { - ResourceType string `json:"resourceType"` // e.g., "schema:CreativeWork" - Label string `json:"label"` - Description string `json:"description"` - Filters []FilterConfig `json:"filters"` - Facets []FacetConfig `json:"facets"` - SortFields []SortConfig `json:"sortFields"` - DefaultSort string `json:"defaultSort"` - DefaultSize int `json:"defaultSize"` - MaxSize int `json:"maxSize"` - AllowFullText bool `json:"allowFullText"` - Metadata map[string]any `json:"metadata,omitempty"` + ResourceType string `json:"resourceType"` // e.g., "schema:CreativeWork" + Label string `json:"label"` + Description string `json:"description"` + Filters []FilterConfig `json:"filters"` + Facets []FacetConfig `json:"facets"` + SortFields []SortConfig `json:"sortFields"` + DefaultSort string `json:"defaultSort"` + DefaultSize int `json:"defaultSize"` + MaxSize int `json:"maxSize"` + AllowFullText bool `json:"allowFullText"` + Metadata map[string]any `json:"metadata,omitempty"` } // SortConfig defines a sortable field. diff --git a/ikuzo/domain/semantic/errors.go b/ikuzo/domain/semantic/errors.go index 094bcd9c..64b022d8 100644 --- a/ikuzo/domain/semantic/errors.go +++ b/ikuzo/domain/semantic/errors.go @@ -52,12 +52,12 @@ func NewValidationError(field, message string, value interface{}) *ValidationErr // HydraError represents a Hydra-compliant error response. type HydraError struct { - TypeValue string `json:"@type"` - Title string `json:"hydra:title"` - Description string `json:"hydra:description"` - StatusCode int `json:"hub3:statusCode,omitempty"` - Details map[string]interface{} `json:"hub3:details,omitempty"` - Documentation string `json:"hub3:documentation,omitempty"` + TypeValue string `json:"@type"` + Title string `json:"hydra:title"` + Description string `json:"hydra:description"` + StatusCode int `json:"hub3:statusCode,omitempty"` + Details map[string]interface{} `json:"hub3:details,omitempty"` + Documentation string `json:"hub3:documentation,omitempty"` } // Type returns the @type for JSON-LD. diff --git a/ikuzo/domain/semantic/store.go b/ikuzo/domain/semantic/store.go index 851bf799..793775c1 100644 --- a/ikuzo/domain/semantic/store.go +++ b/ikuzo/domain/semantic/store.go @@ -273,9 +273,9 @@ func (m *MockIntrospectionStore) IntrospectPaths(_ context.Context, _ *QueryOpti // MockStore is a simple in-memory implementation for testing. type MockStore struct { - results map[string]*SearchResult - contexts map[string]*SearchContext - capabilities StoreCapabilities + results map[string]*SearchResult + contexts map[string]*SearchContext + capabilities StoreCapabilities } // NewMockStore creates a new mock store. diff --git a/ikuzo/domain/semantic/suggest_test.go b/ikuzo/domain/semantic/suggest_test.go index 737ea615..fcf2656a 100644 --- a/ikuzo/domain/semantic/suggest_test.go +++ b/ikuzo/domain/semantic/suggest_test.go @@ -67,43 +67,43 @@ func TestSuggestFields(t *testing.T) { { name: "close typo", unknown: "dc_tilte", - maxDistance: 3, + maxDistance: 3, want: []string{"dc_title", "dc_date", "dc_type"}, }, { name: "no close matches", unknown: "zzzzzzzzz", - maxDistance: 3, + maxDistance: 3, want: nil, }, { name: "multiple close matches", unknown: "dc_tite", - maxDistance: 3, + maxDistance: 3, want: []string{"dc_title", "dc_date", "dc_type"}, }, { name: "exact match excluded", unknown: "dc_title", - maxDistance: 3, + maxDistance: 3, want: []string{"dc_date", "dc_type"}, }, { name: "case sensitive", unknown: "DC_Title", - maxDistance: 3, + maxDistance: 3, want: []string{"dc_title"}, }, { name: "max distance 1", unknown: "dc_titl", - maxDistance: 1, + maxDistance: 1, want: []string{"dc_title"}, }, { name: "max distance 0 returns nil", unknown: "dc_title", - maxDistance: 0, + maxDistance: 0, want: nil, }, } @@ -272,11 +272,11 @@ func TestValidateFilter_WithSuggestions(t *testing.T) { rc.AddFilter(NewFilterConfig("dc_subject", "dc:subject", "Subject").WithOperators(OpEqual)) tests := []struct { - name string - fieldName string - wantErr bool - wantSuggest string // substring expected in error message - noSuggest bool // true if no suggestion expected + name string + fieldName string + wantErr bool + wantSuggest string // substring expected in error message + noSuggest bool // true if no suggestion expected }{ { name: "typo suggests correct field", diff --git a/ikuzo/domain/semantic/template.go b/ikuzo/domain/semantic/template.go index 1b7bf0c3..6c278005 100644 --- a/ikuzo/domain/semantic/template.go +++ b/ikuzo/domain/semantic/template.go @@ -10,9 +10,9 @@ import ( // It provides self-documenting search capabilities by exposing available // search parameters and their constraints. type SearchTemplate struct { - TypeValue string `json:"@type"` - Template string `json:"hydra:template"` - Mapping []TemplateMapping `json:"hydra:mapping"` + TypeValue string `json:"@type"` + Template string `json:"hydra:template"` + Mapping []TemplateMapping `json:"hydra:mapping"` Advanced *AdvancedSearchInfo `json:"hub3:advancedSearch,omitempty"` } diff --git a/ikuzo/driver/gorm/logger.go b/ikuzo/driver/gorm/logger.go index 2bcf9017..b3c8497d 100644 --- a/ikuzo/driver/gorm/logger.go +++ b/ikuzo/driver/gorm/logger.go @@ -106,4 +106,3 @@ func (l *SlogLogger) Trace(ctx context.Context, begin time.Time, fc func() (stri l.Logger.InfoContext(ctx, "GORM query", attrs...) } } - diff --git a/ikuzo/ikuzoctl/cmd/config/elasticsearch.go b/ikuzo/ikuzoctl/cmd/config/elasticsearch.go index 366c6821..5d2cf538 100644 --- a/ikuzo/ikuzoctl/cmd/config/elasticsearch.go +++ b/ikuzo/ikuzoctl/cmd/config/elasticsearch.go @@ -48,11 +48,11 @@ type ElasticSearch struct { // gather elasticsearch metrics Metrics bool `json:"metrics,omitempty"` // elasticsearch client - client *es.Client `json:"client,omitempty"` + client *es.Client // BulkIndexer - bi *esutil.BulkIndexer `json:"bi,omitempty"` + bi *esutil.BulkIndexer // IndexService - is *index.Service `json:"is,omitempty"` + is *index.Service // base of the index aliases IndexName string `json:"indexName,omitempty"` // if non-empty digital objects will be indexed in a dedicated v2 index @@ -62,7 +62,7 @@ type ElasticSearch struct { // number of replicas. default 0 Replicas int `json:"replicas,omitempty"` // logger - logger *logger.CustomLogger `json:"logger,omitempty"` + logger *logger.CustomLogger // UseRemoteIndexer is true when a separate process reads of the queue UseRemoteIndexer bool `json:"useRemoteIndexer,omitempty"` // IndexTypes options are v1, v2, fragment @@ -70,7 +70,7 @@ type ElasticSearch struct { // OrphanWait is the duration in seconds that the orphanDelete will wait for the cluster to be in sync OrphanWait int `json:"orphanWait,omitempty"` // once makes sure that createmapping is only run once - once sync.Once `json:"once,omitempty"` + once sync.Once // UserName is the BasicAuth username UserName string `json:"userName,omitempty"` // Password is the BasicAuth password @@ -224,7 +224,7 @@ func (e *ElasticSearch) NewCustomClient(l *logger.CustomLogger) (*es.Client, err cfg.Password = e.Password cfg.MaxRetries = e.MaxRetries cfg.Timeout = e.ClientTimeOut - + if l != nil { logConv := l.With().Logger() cfg.Logger = &logConv diff --git a/ikuzo/rdf/docs.go b/ikuzo/rdf/docs.go index 38a69b77..0f9f0907 100644 --- a/ikuzo/rdf/docs.go +++ b/ikuzo/rdf/docs.go @@ -1,4 +1,5 @@ -/*package rdf provides tools for the Resource Description Framework (RDF), +/* +package rdf provides tools for the Resource Description Framework (RDF), see https://www.w3.org/RDF/. */ package rdf diff --git a/ikuzo/rdf/formats/html/render.go b/ikuzo/rdf/formats/html/render.go index 5f422c44..9cc74daf 100644 --- a/ikuzo/rdf/formats/html/render.go +++ b/ikuzo/rdf/formats/html/render.go @@ -143,4 +143,3 @@ func RenderRDF(w http.ResponseWriter, r *http.Request, g *rdf.Graph) error { return err } - diff --git a/ikuzo/rdf/formats/jsonld/serializer_test.go b/ikuzo/rdf/formats/jsonld/serializer_test.go index 95de6f69..856ecd54 100644 --- a/ikuzo/rdf/formats/jsonld/serializer_test.go +++ b/ikuzo/rdf/formats/jsonld/serializer_test.go @@ -158,4 +158,3 @@ func keys(m map[string]any) []string { } return out } - diff --git a/ikuzo/rdf/formats/mappingxml/serializer_test.go b/ikuzo/rdf/formats/mappingxml/serializer_test.go index e7e75fb9..4bdecec0 100644 --- a/ikuzo/rdf/formats/mappingxml/serializer_test.go +++ b/ikuzo/rdf/formats/mappingxml/serializer_test.go @@ -68,27 +68,27 @@ func TestSerialize(t *testing.T) { func TestExcludePrefixes(t *testing.T) { is := is.New(t) - + // Create a simple graph for testing g := rdf.NewGraph() g.UseIndex = true g.UseResource = true - + // Add some test triples with different prefixes subj1, _ := rdf.NewIRI("https://example.com/resource1") subj2, _ := rdf.NewIRI("http://schemas.delving.eu/nave/terms/resource2") pred1, _ := rdf.NewIRI("https://example.com/predicate1") pred2, _ := rdf.NewIRI("http://schemas.delving.eu/nave/terms/predicate2") obj, _ := rdf.NewLiteral("test value") - + g.Add(rdf.NewTriple(subj1, pred1, obj)) g.Add(rdf.NewTriple(subj2, pred1, obj)) g.Add(rdf.NewTriple(subj1, pred2, obj)) - + // Test filtering subjects with excluded prefix cfg := &FilterConfig{ExcludePrefixes: []string{"http://schemas.delving.eu/nave/terms/"}} filtered := filterResources(g.Resources(), cfg) - + // Should only have the resource with subject1 (not the one with delving prefix) is.Equal(len(filtered), 1) is.Equal(filtered[0].Subject().RawValue(), "https://example.com/resource1") @@ -96,27 +96,27 @@ func TestExcludePrefixes(t *testing.T) { func TestExcludePrefixesSerialization(t *testing.T) { is := is.New(t) - + // Load existing test data which already has proper namespaces g := rdf.NewGraph() g.UseIndex = true g.UseResource = true - + f, err := os.Open("testdata/rdf.nt") is.NoErr(err) defer f.Close() _, err = ntriples.Parse(f, g) is.NoErr(err) - + // Test serialization with subject filtering (filter out klek.si resources) cfg := &FilterConfig{ExcludePrefixes: []string{"https://klek.si/"}} - + var buf bytes.Buffer err = Serialize(g, &buf, cfg) is.NoErr(err) - + xmlOutput := buf.String() - + // Should NOT contain the excluded subject is.True(!strings.Contains(xmlOutput, "https://klek.si/")) // Should contain the other resource @@ -125,12 +125,12 @@ func TestExcludePrefixesSerialization(t *testing.T) { func TestExcludeTypePrefixes(t *testing.T) { is := is.New(t) - + // Create a simple graph for testing g := rdf.NewGraph() g.UseIndex = true g.UseResource = true - + // Add some test triples with different types subj1, _ := rdf.NewIRI("https://example.com/resource1") subj2, _ := rdf.NewIRI("https://example.com/resource2") @@ -138,22 +138,22 @@ func TestExcludeTypePrefixes(t *testing.T) { type2, _ := rdf.NewIRI("http://schemas.delving.eu/nave/terms/SomeType") pred1, _ := rdf.NewIRI("https://schema.org/name") obj, _ := rdf.NewLiteral("test value") - + // Add rdf:type triples g.Add(rdf.NewTriple(subj1, rdf.IsA, type1)) g.Add(rdf.NewTriple(subj2, rdf.IsA, type2)) // Add other predicates g.Add(rdf.NewTriple(subj1, pred1, obj)) g.Add(rdf.NewTriple(subj2, pred1, obj)) - + // Test filtering resources with excluded type prefixes cfg := &FilterConfig{ExcludeTypePrefixes: []string{"http://schemas.delving.eu/nave/terms/"}} filtered := filterResources(g.Resources(), cfg) - + // Should only have the resource with type1 (not the one with delving type) is.Equal(len(filtered), 1) is.Equal(filtered[0].Subject().RawValue(), "https://example.com/resource1") - + // Verify the remaining resource has the correct type types := filtered[0].Types() is.Equal(len(types), 1) @@ -162,45 +162,45 @@ func TestExcludeTypePrefixes(t *testing.T) { func TestCombinedPrefixFilters(t *testing.T) { is := is.New(t) - + // Create a graph with resources that should be filtered by different criteria g := rdf.NewGraph() g.UseIndex = true g.UseResource = true - + // Resource 1: valid subject, valid type, valid predicate subj1, _ := rdf.NewIRI("https://example.com/resource1") type1, _ := rdf.NewIRI("https://schema.org/CreativeWork") pred1, _ := rdf.NewIRI("https://schema.org/name") - + // Resource 2: has excluded subject prefix subj2, _ := rdf.NewIRI("http://schemas.delving.eu/nave/terms/resource2") type2, _ := rdf.NewIRI("https://schema.org/CreativeWork") - + // Resource 3: has excluded type prefix subj3, _ := rdf.NewIRI("https://example.com/resource3") type3, _ := rdf.NewIRI("http://schemas.delving.eu/nave/terms/SomeType") - + obj, _ := rdf.NewLiteral("test value") - + // Add triples g.Add(rdf.NewTriple(subj1, rdf.IsA, type1)) g.Add(rdf.NewTriple(subj1, pred1, obj)) - + g.Add(rdf.NewTriple(subj2, rdf.IsA, type2)) g.Add(rdf.NewTriple(subj2, pred1, obj)) - + g.Add(rdf.NewTriple(subj3, rdf.IsA, type3)) g.Add(rdf.NewTriple(subj3, pred1, obj)) - + // Test filtering with both ExcludePrefixes and ExcludeTypePrefixes cfg := &FilterConfig{ ExcludePrefixes: []string{"http://schemas.delving.eu/nave/terms/"}, ExcludeTypePrefixes: []string{"http://schemas.delving.eu/nave/terms/"}, } filtered := filterResources(g.Resources(), cfg) - + // Should only have resource1 (resource2 excluded by subject, resource3 excluded by type) is.Equal(len(filtered), 1) is.Equal(filtered[0].Subject().RawValue(), "https://example.com/resource1") -} \ No newline at end of file +} diff --git a/ikuzo/rdf/formats/rdfxml/internal/rdf/rdf.go b/ikuzo/rdf/formats/rdfxml/internal/rdf/rdf.go index 14993b23..67edfdd2 100644 --- a/ikuzo/rdf/formats/rdfxml/internal/rdf/rdf.go +++ b/ikuzo/rdf/formats/rdfxml/internal/rdf/rdf.go @@ -1,38 +1,39 @@ // Package rdf provides functionality for working with RDF resources, including // parsing and serialization of the various RDF formats. // -// Data model +// # Data model // // The package adhers to the RDF data model as described in http://www.w3.org/TR/rdf11-concepts/. // -// Data structures +// # Data structures // // TODO. // -// Encoding and decoding +// # Encoding and decoding // // The package aims to support all the RDF serialization formats standardized by W3C. Currently the following are implemented: -// Format | Decode | Encode -// -----------|--------|-------- -// RDF/XML | x | - -// N-Triples | x | x -// N-Quads | x | x -// Turtle | x | x -// TriG | - | - -// JSON-LD | - | - +// +// Format | Decode | Encode +// -----------|--------|-------- +// RDF/XML | x | - +// N-Triples | x | x +// N-Quads | x | x +// Turtle | x | x +// TriG | - | - +// JSON-LD | - | - // // The parsers are implemented as streaming decoders, consuming an io.Reader // and emitting triples/quads as soon as they are available. Simply call // Decode() until the reader is exhausted and emits io.EOF: // -// f, err := os.Open("mytriples.ttl") -// if err != nil { -// // handle error -// } -// dec := rdf.NewTripleDecoder(f, rdf.Turtle) -// for triple, err := dec.Decode(); err != io.EOF; triple, err = dec.Decode() { -// // do something with triple .. -// } +// f, err := os.Open("mytriples.ttl") +// if err != nil { +// // handle error +// } +// dec := rdf.NewTripleDecoder(f, rdf.Turtle) +// for triple, err := dec.Decode(); err != io.EOF; triple, err = dec.Decode() { +// // do something with triple .. +// } // // The encoders work similarily. // For a complete working example, see the rdf2rdf application, which converts between different serialization formats using the decoders and encoders of the rdf package: https://github.com/knakk/rdf2rdf. diff --git a/ikuzo/rdf/formats/rdfxml/internal/rdf/ttl_test.go b/ikuzo/rdf/formats/rdfxml/internal/rdf/ttl_test.go index 168e31b1..9358a35e 100644 --- a/ikuzo/rdf/formats/rdfxml/internal/rdf/ttl_test.go +++ b/ikuzo/rdf/formats/rdfxml/internal/rdf/ttl_test.go @@ -1758,7 +1758,7 @@ p:a·̀ͯ‿.⁀ .`, "", []Triple{ Triple{ Subj: IRI{str: "http://a.example/s"}, Pred: IRI{str: "http://a.example/p"}, - Obj: Literal{str: ` `, DataType: xsdString}, + Obj: Literal{str: ` `, DataType: xsdString}, }, }}, @@ -1774,7 +1774,7 @@ p:a·̀ͯ‿.⁀ .`, "", []Triple{ Triple{ Subj: IRI{str: "http://a.example/s"}, Pred: IRI{str: "http://a.example/p"}, - Obj: Literal{str: "", DataType: xsdString}, + Obj: Literal{str: "", DataType: xsdString}, }, }}, diff --git a/ikuzo/rdf/index/entry_test.go b/ikuzo/rdf/index/entry_test.go index c6fa1045..4b364459 100644 --- a/ikuzo/rdf/index/entry_test.go +++ b/ikuzo/rdf/index/entry_test.go @@ -394,4 +394,4 @@ func TestEntry_ResolvedFields_OmitEmpty(t *testing.T) { if strings.Contains(jsonStr, "resolvedLevel") { t.Error("resolvedLevel should be omitted when zero") } -} \ No newline at end of file +} diff --git a/ikuzo/rdf/index/graph.go b/ikuzo/rdf/index/graph.go index 65927e50..dd9929ed 100644 --- a/ikuzo/rdf/index/graph.go +++ b/ikuzo/rdf/index/graph.go @@ -47,10 +47,10 @@ type Graph struct { // roots are the ids of the root resources of the Graph roots []*Resource - + // entryOrder tracks the global order counter for entries to ensure consistent ordering entryOrder int - + // mu protects the entryOrder counter for concurrent access mu sync.Mutex } @@ -148,7 +148,7 @@ func (g *Graph) IndexMessage(tagMap *TagMap) (*domainpb.IndexMessage, error) { return nil, err } } - + // Set entry levels based on resource context depth g.setEntryLevels() diff --git a/ikuzo/rdf/index/graph_query_test.go b/ikuzo/rdf/index/graph_query_test.go index e5de3746..3753d541 100644 --- a/ikuzo/rdf/index/graph_query_test.go +++ b/ikuzo/rdf/index/graph_query_test.go @@ -149,4 +149,3 @@ func verifyQueryResults(t *testing.T, result *QueryResult, expectedResourceID st is.True(found) // Expected entry value should be found } } - diff --git a/ikuzo/rdf/index/graph_test.go b/ikuzo/rdf/index/graph_test.go index 33c00a9f..2e0e0f41 100644 --- a/ikuzo/rdf/index/graph_test.go +++ b/ikuzo/rdf/index/graph_test.go @@ -304,7 +304,7 @@ func TestGraph_MarshalWithFields(t *testing.T) { // Convert to map for inspection fieldsMap, ok := fields.(map[string]interface{}) is.True(ok) - + // Check that both searchLabels are included as keys (not predicates) titleValues, ok := fieldsMap["dc_title"].([]interface{}) is.True(ok) diff --git a/ikuzo/rdf/index/label_resolver_test.go b/ikuzo/rdf/index/label_resolver_test.go index 9ce10cb3..5ad98560 100644 --- a/ikuzo/rdf/index/label_resolver_test.go +++ b/ikuzo/rdf/index/label_resolver_test.go @@ -6,22 +6,22 @@ import ( func TestGraph_ResolveLabels(t *testing.T) { const ( - dcTitle = "http://purl.org/dc/elements/1.1/title" - skosPref = "http://www.w3.org/2004/02/skos/core#prefLabel" - rdfsLabel = "http://www.w3.org/2000/01/rdf-schema#label" - foafName = "http://xmlns.com/foaf/0.1/name" - foafKnows = "http://xmlns.com/foaf/0.1/knows" - dcCreator = "http://purl.org/dc/elements/1.1/creator" - dcSubject = "http://purl.org/dc/elements/1.1/subject" - dcRelation = "http://purl.org/dc/elements/1.1/relation" + dcTitle = "http://purl.org/dc/elements/1.1/title" + skosPref = "http://www.w3.org/2004/02/skos/core#prefLabel" + rdfsLabel = "http://www.w3.org/2000/01/rdf-schema#label" + foafName = "http://xmlns.com/foaf/0.1/name" + foafKnows = "http://xmlns.com/foaf/0.1/knows" + dcCreator = "http://purl.org/dc/elements/1.1/creator" + dcSubject = "http://purl.org/dc/elements/1.1/subject" + dcRelation = "http://purl.org/dc/elements/1.1/relation" dcDescription = "http://purl.org/dc/elements/1.1/description" ) tests := []struct { name string resources []*Resource - targetRscIdx int // index of resource to check - targetEntryIdx int // index of entry to check within that resource + targetRscIdx int // index of resource to check + targetEntryIdx int // index of entry to check within that resource wantValue string wantLang string wantResolved string // expected ResolvedFrom diff --git a/ikuzo/rdf/index/resource.go b/ikuzo/rdf/index/resource.go index f9afd3c0..288fbfd0 100644 --- a/ikuzo/rdf/index/resource.go +++ b/ikuzo/rdf/index/resource.go @@ -222,7 +222,7 @@ func entryFromObject(pred rdf.Predicate, obj rdf.Object) *Entry { switch obj.Type() { case rdf.TermBlankNode: - e.ID = obj.String() // Use String() to get _: prefix for blank nodes + e.ID = obj.String() // Use String() to get _: prefix for blank nodes e.EntryType = Bnode case rdf.TermIRI: e.ID = obj.RawValue() diff --git a/ikuzo/rdf/index/tags.go b/ikuzo/rdf/index/tags.go index b566e66a..e2cfbf3f 100644 --- a/ikuzo/rdf/index/tags.go +++ b/ikuzo/rdf/index/tags.go @@ -21,15 +21,15 @@ func NewTagMap() *TagMap { // FromMap creates a TagMap from a map of predicate URIs to tag slices func NewTagMapFromMap(m map[string][]string) *TagMap { tm := NewTagMap() - + if m == nil { return tm } - + for uri, tags := range m { tm.AddTags(uri, tags...) } - + return tm } @@ -37,13 +37,13 @@ func NewTagMapFromMap(m map[string][]string) *TagMap { func (tm *TagMap) AddTags(predicateURI string, tags ...string) { tm.Lock() defer tm.Unlock() - + current, exists := tm.predicateToTags[predicateURI] if !exists { tm.predicateToTags[predicateURI] = tags return } - + // Add only unique tags for _, tag := range tags { if !containsTag(current, tag) { @@ -57,12 +57,12 @@ func (tm *TagMap) AddTags(predicateURI string, tags ...string) { func (tm *TagMap) GetTags(predicateURI string) []string { tm.RLock() defer tm.RUnlock() - + tags, exists := tm.predicateToTags[predicateURI] if !exists { return nil } - + return tags } @@ -70,7 +70,7 @@ func (tm *TagMap) GetTags(predicateURI string) []string { func (tm *TagMap) Len() int { tm.RLock() defer tm.RUnlock() - + return len(tm.predicateToTags) } @@ -79,12 +79,12 @@ func (tm *TagMap) ApplyTagsToEntry(entry *Entry) { if entry == nil { return } - + tags := tm.GetTags(entry.Predicate) if len(tags) == 0 { return } - + entry.AddTags(tags...) } @@ -103,7 +103,7 @@ func (g *Graph) ApplyTags(tagMap *TagMap) { if tagMap == nil || tagMap.Len() == 0 { return } - + count := 0 processedCount := 0 for _, resource := range g.Resources { @@ -120,10 +120,10 @@ func (g *Graph) ApplyTags(tagMap *TagMap) { } } } - - slog.Debug("Applied tags to entries", - "count", count, - "processed", processedCount, + + slog.Debug("Applied tags to entries", + "count", count, + "processed", processedCount, "total_resources", len(g.Resources)) } @@ -135,9 +135,9 @@ func (g *Graph) SetContextAndTags(tagMap *TagMap) error { return err } } - + // Then apply tags g.ApplyTags(tagMap) - + return nil -} \ No newline at end of file +} diff --git a/ikuzo/rdf/index/tags_test.go b/ikuzo/rdf/index/tags_test.go index 176caa46..2347645b 100644 --- a/ikuzo/rdf/index/tags_test.go +++ b/ikuzo/rdf/index/tags_test.go @@ -58,18 +58,18 @@ func TestTagMap_ApplyTagsToEntry(t *testing.T) { // Check if processTags works for isoDate and dateRange err := dateEntry.processTags() is.NoErr(err) - + // Since this entry has both isoDate and dateRange tags, we expect 3 entries in the Date array: // 1. From isoDate: the original value "2020-01-01" // 2. From dateRange: Greater value "2020-01-01" // 3. From dateRange: Less value "2020-01-01" (for single date value, Greater and Less are same) is.Equal(len(dateEntry.Date), 3) - + // Verify that DateRange is set is.True(dateEntry.DateRange != nil) is.Equal(dateEntry.DateRange.Greater, "2020-01-01") is.Equal(dateEntry.DateRange.Less, "2020-01-01") - + // Test date range entry dateRangeEntry := &Entry{ Predicate: "http://purl.org/dc/elements/1.1/date", @@ -77,7 +77,7 @@ func TestTagMap_ApplyTagsToEntry(t *testing.T) { EntryType: Literal, Tags: []string{"dateRange"}, } - + // Process tags for date range err = dateRangeEntry.processTags() is.NoErr(err) @@ -158,16 +158,16 @@ func TestGraph_ApplyTags(t *testing.T) { is.Equal(resource1.Entries[1].Tags[0], "latLong") is.Equal(len(resource1.Entries[2].Tags), 0) // title entry, no tags - + // Check that processTags was called and TypeIndexFields were set // Since the entry has both isoDate and dateRange tags, it should have 3 entries in the Date array - is.Equal(len(resource1.Entries[0].Date), 3) - + is.Equal(len(resource1.Entries[0].Date), 3) + // Also verify that DateRange is set correctly is.True(resource1.Entries[0].DateRange != nil) is.Equal(resource1.Entries[0].DateRange.Greater, "2020-01-01") is.Equal(resource1.Entries[0].DateRange.Less, "2020-01-01") - + is.Equal(resource1.Entries[1].LatLong, "52.3676, 4.9041") // latLong field set } @@ -231,11 +231,11 @@ func TestGraph_SetContextAndTags(t *testing.T) { is.Equal(len(childResource.Entries[0].Tags), 2) is.Equal(childResource.Entries[0].Tags[0], "dateRange") is.Equal(childResource.Entries[0].Tags[1], "isoDate") - + // Verify TypeIndexField is set for date entry // Since the entry has both isoDate and dateRange tags, it should have 3 entries in the Date array is.Equal(len(childResource.Entries[0].Date), 3) - + // Also verify that DateRange is set correctly is.True(childResource.Entries[0].DateRange != nil) is.Equal(childResource.Entries[0].DateRange.Greater, "2020-01-01") @@ -243,7 +243,7 @@ func TestGraph_SetContextAndTags(t *testing.T) { // Verify context is set flag is.Equal(g.contextIsSet, true) - + // Note: Actual context values depend on how the test environment handles them // In some cases, the actual context references might not be populated, // but we've already verified that the contextIsSet flag is true @@ -254,7 +254,7 @@ func TestNewTagMapFromMap(t *testing.T) { // Create a map of predicate URIs to tags m := map[string][]string{ - "http://purl.org/dc/elements/1.1/date": {"dateRange", "isoDate"}, + "http://purl.org/dc/elements/1.1/date": {"dateRange", "isoDate"}, "http://www.w3.org/2003/01/geo/wgs84_pos#lat_long": {"latLong"}, } @@ -335,4 +335,4 @@ func TestGraph_IndexMessageWithTags(t *testing.T) { // Verify TypeIndexField is set for date entry is.Equal(len(rootResource.Entries[0].Date), 1) // Only isoDate tag is used for this test is.Equal(rootResource.Entries[0].Date[0], "2020-01-01") -} \ No newline at end of file +} diff --git a/ikuzo/search/facet.go b/ikuzo/search/facet.go index 77fddf24..07e258c7 100644 --- a/ikuzo/search/facet.go +++ b/ikuzo/search/facet.go @@ -53,23 +53,27 @@ type FacetField struct { // The following modifiers are supported: // // ^ prefix reverse the sort-order of the facet. The default sort-order is -// descending. -// Example: ^dc_title. +// +// descending. +// Example: ^dc_title. // // @ suffix sorts the facets on the key. The default is to sort on the count, -// i.e. the number of records in which the facet value is found. -// Example: dc_title@ +// +// i.e. the number of records in which the facet value is found. +// Example: dc_title@ // // ~ sets the number of facets that are returned. If not set the default value -// from the search.Service is used. -// Example: dc_title~10 +// +// from the search.Service is used. +// Example: dc_title~10 // // In the fields, the '.' is used as a field-separator to define section and // subfield. The following sections are supported: // // meta: is the header section that included with every search record // tree: is the section to support search in hierarchical structures such as -// EAD and SKOS. +// +// EAD and SKOS. // // The default section is 'resources.entries', which does not need to be explicitly // added. When a '.' separated prefix is absent 'resources.entries' is added. diff --git a/ikuzo/search/filter.go b/ikuzo/search/filter.go index c75c8f57..e27d5884 100644 --- a/ikuzo/search/filter.go +++ b/ikuzo/search/filter.go @@ -18,8 +18,6 @@ package search // // It supports both first level objects such as 'Meta' and 'Tree' and nested // items from resource.entries via a NestedFilter. -// -// type Filter struct { // SearchLabel is a short namespaced version of a URI. Field string `json:"searchLabel,omitempty"` diff --git a/ikuzo/search/paginator.go b/ikuzo/search/paginator.go index ea1efd29..8a266e80 100644 --- a/ikuzo/search/paginator.go +++ b/ikuzo/search/paginator.go @@ -97,11 +97,11 @@ func (p *Paginator) AddPageLinks() error { func (p *Paginator) getPageLinks() ([]PageLink, error) { totalLinksWanted := 10 - + // Calculate the ideal window firstPage := 1 lastPage := p.LastPage - + if p.LastPage <= totalLinksWanted { // If total pages <= 10, show all pages firstPage = 1 @@ -110,13 +110,13 @@ func (p *Paginator) getPageLinks() ([]PageLink, error) { // Try to center the current page with 5 on each side firstPage = p.CurrentPage - 5 lastPage = p.CurrentPage + 4 - + // Adjust if we're too close to the beginning if firstPage < 1 { firstPage = 1 lastPage = totalLinksWanted } - + // Adjust if we're too close to the end if lastPage > p.LastPage { lastPage = p.LastPage diff --git a/ikuzo/search/service.go b/ikuzo/search/service.go index 0ae8eeb3..1d57f850 100644 --- a/ikuzo/search/service.go +++ b/ikuzo/search/service.go @@ -36,9 +36,9 @@ type OptionFunc func(*Service) error // // Example: // -// service, err := search.NewService( -// search.ResponseSize(20), -// ) +// service, err := search.NewService( +// search.ResponseSize(20), +// ) // // An error is also returned when some configuration option is invalid. func NewService(options ...OptionFunc) (*Service, error) { diff --git a/ikuzo/service/x/bulk/errors.go b/ikuzo/service/x/bulk/errors.go index bcbe4ccc..6555e6b5 100644 --- a/ikuzo/service/x/bulk/errors.go +++ b/ikuzo/service/x/bulk/errors.go @@ -24,9 +24,9 @@ type BulkError struct { OrgID string `json:"orgId,omitempty"` DatasetID string `json:"datasetId,omitempty"` LocalID string `json:"localId,omitempty"` - Stage string `json:"stage"` // Processing stage: "validation", "rdf_parse", "indexing", etc. - Message string `json:"message"` // Human-readable error message - Detail string `json:"detail,omitempty"` // Original error detail (e.g., "invalid language tag: unexpected character: ' '") + Stage string `json:"stage"` // Processing stage: "validation", "rdf_parse", "indexing", etc. + Message string `json:"message"` // Human-readable error message + Detail string `json:"detail,omitempty"` // Original error detail (e.g., "invalid language tag: unexpected character: ' '") cause error // Underlying error (not serialized) } diff --git a/ikuzo/service/x/bulk/handle_bulk_debug.go b/ikuzo/service/x/bulk/handle_bulk_debug.go index 2f657c57..538ebbb8 100644 --- a/ikuzo/service/x/bulk/handle_bulk_debug.go +++ b/ikuzo/service/x/bulk/handle_bulk_debug.go @@ -67,7 +67,6 @@ func (s *Service) handleBulkDebug(w http.ResponseWriter, r *http.Request) { return } - if format == "resourceMap" { render.JSON(w, r, rm.Resources()) return diff --git a/ikuzo/service/x/bulk/handle_cleanup.go b/ikuzo/service/x/bulk/handle_cleanup.go index c972df82..eb5529f5 100644 --- a/ikuzo/service/x/bulk/handle_cleanup.go +++ b/ikuzo/service/x/bulk/handle_cleanup.go @@ -32,14 +32,14 @@ type DatasetCleanupResult struct { // GlobalCleanupResponse contains the result of a global orphan cleanup operation type GlobalCleanupResponse struct { - Status string `json:"status"` - OrgID string `json:"orgID"` - TotalDatasets int `json:"totalDatasets"` - WithOrphans int `json:"withOrphans"` - CleanedUp int `json:"cleanedUp"` - Errors int `json:"errors"` - Skipped int `json:"skipped"` - Results []DatasetCleanupResult `json:"results"` + Status string `json:"status"` + OrgID string `json:"orgID"` + TotalDatasets int `json:"totalDatasets"` + WithOrphans int `json:"withOrphans"` + CleanedUp int `json:"cleanedUp"` + Errors int `json:"errors"` + Skipped int `json:"skipped"` + Results []DatasetCleanupResult `json:"results"` } // handleCleanupOrphans handles POST /api/admin/cleanup-orphans/{orgID}/{datasetID} diff --git a/ikuzo/service/x/bulk/request.go b/ikuzo/service/x/bulk/request.go index 146eb220..e3d6644c 100644 --- a/ikuzo/service/x/bulk/request.go +++ b/ikuzo/service/x/bulk/request.go @@ -48,9 +48,9 @@ type Request struct { // ExpectedRecords carries the client's expected index size for the // index_verify action (registry-owned completion signal). ExpectedRecords int `json:"expectedRecords,omitempty"` - aboutTypeURI []string - resolvedTags []string - indexTypes []string + aboutTypeURI []string + resolvedTags []string + indexTypes []string } func (req *Request) valid() error { diff --git a/ikuzo/service/x/imageproxy/request.go b/ikuzo/service/x/imageproxy/request.go index 7487d3f1..0b4e9187 100644 --- a/ikuzo/service/x/imageproxy/request.go +++ b/ikuzo/service/x/imageproxy/request.go @@ -226,7 +226,7 @@ func (req *Request) Read(path string) (io.ReadCloser, error) { } else if strings.HasSuffix(path, ".jpeg") { alternatePath = strings.TrimSuffix(path, ".jpeg") + ".jpg" } - + if alternatePath != "" { if f, altErr := os.Open(alternatePath); altErr == nil { return f, nil diff --git a/ikuzo/service/x/imageproxy/service.go b/ikuzo/service/x/imageproxy/service.go index 7946e1ab..dbd05f73 100644 --- a/ikuzo/service/x/imageproxy/service.go +++ b/ikuzo/service/x/imageproxy/service.go @@ -143,31 +143,31 @@ func (s *Service) getVipsPath() string { } s.log.Warn().Str("path", s.vipsPath).Msg("custom vips path not found") } - + if s.vipsCliPath != "" { if _, err := os.Stat(s.vipsCliPath); err == nil { return s.vipsCliPath } s.log.Warn().Str("path", s.vipsCliPath).Msg("custom vips-cli path not found") } - + if path, err := exec.LookPath("vips"); err == nil { return path } - + return "" } func (s *Service) deepZoomExternally(from string) error { cleanFrom := strings.TrimSuffix(from, ".dzi") - + vipsPath := s.getVipsPath() if vipsPath == "" { return fmt.Errorf("vips binary not found") } var args []string - + // Check if using vips-cli which has different command structure if strings.Contains(vipsPath, "vips-cli") { args = []string{ @@ -186,7 +186,7 @@ func (s *Service) deepZoomExternally(from string) error { cmd := exec.Command(vipsPath, args...) s.log.Info().Str("command", vipsPath).Strs("args", args).Str("from", cleanFrom).Msg("executing dzsave command") - + err := cmd.Run() if err != nil { s.log.Error().Err(err).Str("command", vipsPath).Strs("args", args).Msg("dzsave command failed") @@ -411,7 +411,7 @@ func (s *Service) Do(ctx context.Context, req *Request, w io.Writer) error { // check cache cachePath := req.cacheKeyPath() s.log.Debug().Str("cachePath", cachePath).Str("sourceURL", req.SourceURL).Str("subPath", req.SubPath).Msg("attempting to read from cache") - + r, err := req.Read(cachePath) if err != nil && !errors.Is(err, ErrCacheKeyNotFound) { s.log.Error().Err(err).Str("url", req.SourceURL).Str("cachePath", cachePath).Msg("unexpected error reading from cache") diff --git a/ikuzo/service/x/index/service.go b/ikuzo/service/x/index/service.go index 16f441f2..127a6149 100644 --- a/ikuzo/service/x/index/service.go +++ b/ikuzo/service/x/index/service.go @@ -46,7 +46,7 @@ type BulkIndex interface { } type Service struct { - bi esutil.BulkIndexer + bi esutil.BulkIndexer // per-dataset indexing failures collected from BulkIndexer OnFailure, // drained into the next verification notification (key: org|dataset) diff --git a/ikuzo/service/x/pid/task.go b/ikuzo/service/x/pid/task.go index 9ece1b7d..10fef09e 100644 --- a/ikuzo/service/x/pid/task.go +++ b/ikuzo/service/x/pid/task.go @@ -17,7 +17,7 @@ func (s *Service) registerTaskHandlers() error { if s.ts == nil { return fmt.Errorf("task service is nil") } - + s.log.Info().Msg("scheduling sync task handlers") s.ts.RegisterWorkerFunc(pidSavetype, s.HandleSavePidTask) return nil diff --git a/ikuzo/service/x/semantic/documentation.go b/ikuzo/service/x/semantic/documentation.go index 997cfbde..7e023f61 100644 --- a/ikuzo/service/x/semantic/documentation.go +++ b/ikuzo/service/x/semantic/documentation.go @@ -117,9 +117,9 @@ func (s *Service) buildAPIDocumentation(r *http.Request) map[string]any { baseURL := s.buildBaseURL(r) doc := map[string]any{ - "@context": semantic.DefaultContext(), - "@id": baseURL + "/docs", - "@type": "hydra:ApiDocumentation", + "@context": semantic.DefaultContext(), + "@id": baseURL + "/docs", + "@type": "hydra:ApiDocumentation", "hydra:title": "Hub3 Semantic Search API - Complete Documentation", "hydra:description": "Complete API documentation including all resource types, supported filters, " + "facets, operators, and detailed examples. For a quick overview, visit the root endpoint.", @@ -173,10 +173,10 @@ func (s *Service) buildSupportedClasses(r *http.Request) []map[string]any { } class := map[string]any{ - "@id": resourceType, - "@type": "hydra:Class", - "hydra:title": config.Label, - "hydra:description": config.Description, + "@id": resourceType, + "@type": "hydra:Class", + "hydra:title": config.Label, + "hydra:description": config.Description, "hub3:searchEndpoint": fmt.Sprintf("%s%s/type/%s/search", getScheme(r), r.Host, resourceType), "hub3:docsEndpoint": fmt.Sprintf("%s%s/type/%s/docs", getScheme(r), r.Host, resourceType), } @@ -412,11 +412,11 @@ func (s *Service) buildTypeDocumentation(r *http.Request, config *semantic.Resou sortFields := make([]map[string]any, 0, len(config.SortFields)) for _, sort := range config.SortFields { sortFields = append(sortFields, map[string]any{ - "@type": "hub3:SortField", - "hub3:field": sort.Field, - "hydra:property": sort.PropertyURI, - "hydra:title": sort.Label, - "hub3:defaultDir": sort.DefaultDir, + "@type": "hub3:SortField", + "hub3:field": sort.Field, + "hydra:property": sort.PropertyURI, + "hydra:title": sort.Label, + "hub3:defaultDir": sort.DefaultDir, }) } if len(sortFields) > 0 { diff --git a/ikuzo/service/x/sitemap/docs.go b/ikuzo/service/x/sitemap/docs.go index b78e53fc..48e74628 100644 --- a/ikuzo/service/x/sitemap/docs.go +++ b/ikuzo/service/x/sitemap/docs.go @@ -6,15 +6,16 @@ It requires an implementation of the Store interface to render content. All sitemap formats limit a single sitemap to 10MB (uncompressed) and 50,000 URLs. For a single Sitemap index file, the maximum capacity of URLs and storage - could be calculated as described below: - in terms of URLs: + could be calculated as described below: - 50,000 sitemaps = ( 50,000 * 50,000 ) URLs = 2,500,000,000 URLs + in terms of URLs: - in terms of size: + 50,000 sitemaps = ( 50,000 * 50,000 ) URLs = 2,500,000,000 URLs - 50MB + (50,000 sitemaps * 50MB) = 2,500,050 MB = > 2.3 TB + in terms of size: + + 50MB + (50,000 sitemaps * 50MB) = 2,500,050 MB = > 2.3 TB These limits are enforced by the http.Handlers in this package. */ diff --git a/ikuzo/service/x/sparql/repo_harvest.go b/ikuzo/service/x/sparql/repo_harvest.go index 105c220c..65cce43f 100644 --- a/ikuzo/service/x/sparql/repo_harvest.go +++ b/ikuzo/service/x/sparql/repo_harvest.go @@ -87,14 +87,14 @@ func (l *retryLogger) Warn(msg string, keysAndValues ...interface{}) { // HarvestMetrics tracks timing and progress statistics during harvest type HarvestMetrics struct { - StartTime time.Time - TotalFetchTime time.Duration - TotalParseTime time.Duration - RequestCount int64 - SuccessCount int64 - FailCount int64 - TotalTriples int64 - mu sync.Mutex + StartTime time.Time + TotalFetchTime time.Duration + TotalParseTime time.Duration + RequestCount int64 + SuccessCount int64 + FailCount int64 + TotalTriples int64 + mu sync.Mutex } func (m *HarvestMetrics) Add(fetchTime, parseTime time.Duration, triples int, success bool) { @@ -178,26 +178,26 @@ type HarvestConfig struct { IncrementalWhereClause string // using the From timestamp to harvest an incremental set GetGraphQuery string // sparql query to get full graph. ?subject is injected for each } - From time.Time // the time of the last harvest - GraphMimeType string // if the subject can be harvested directly which mime-type to use - MaxSubjects int - PageSize int - TotalSizeSubjects int - HarvestErrors map[string]*HarvestError - DereferencePredicates []string // List of predicate URIs whose object IRIs should be dereferenced - DereferenceMaxDepth int // Maximum depth for recursive dereferencing (default 1) - ForceHarvest bool // Force harvest regardless of revision check - rw sync.RWMutex - client *http.Client - OutputDir string - LastCheck time.Time - TargetDatasets map[string]int - Tags []string - repo *sparql.Repo - AboutTypeURI string - Metrics *HarvestMetrics `toml:"-"` // runtime only, not persisted - dereferencePredicates map[string]bool // internal lookup map - dereferenceCache *DereferenceCache // cache for dereferenced graphs + From time.Time // the time of the last harvest + GraphMimeType string // if the subject can be harvested directly which mime-type to use + MaxSubjects int + PageSize int + TotalSizeSubjects int + HarvestErrors map[string]*HarvestError + DereferencePredicates []string // List of predicate URIs whose object IRIs should be dereferenced + DereferenceMaxDepth int // Maximum depth for recursive dereferencing (default 1) + ForceHarvest bool // Force harvest regardless of revision check + rw sync.RWMutex + client *http.Client + OutputDir string + LastCheck time.Time + TargetDatasets map[string]int + Tags []string + repo *sparql.Repo + AboutTypeURI string + Metrics *HarvestMetrics `toml:"-"` // runtime only, not persisted + dereferencePredicates map[string]bool // internal lookup map + dereferenceCache *DereferenceCache // cache for dereferenced graphs } func (cfg *HarvestConfig) AddError(subject string, err error) { @@ -645,7 +645,7 @@ func HarvestGraphs(ctx context.Context, cfg *HarvestConfig, cb func(g *rdf.Graph // Initialize dereference predicates lookup map cfg.initDereferencePredicates() - subjects := make(chan string, 100) // buffered channel to prevent blocking + subjects := make(chan string, 100) // buffered channel to prevent blocking g, gCtx := errgroup.WithContext(ctx) // Use errgroup context for proper cancellation propagation // Produce diff --git a/ikuzo/storage/x/elasticsearch8/aggregation_builder_test.go b/ikuzo/storage/x/elasticsearch8/aggregation_builder_test.go index c75ba0e2..06f3fd40 100644 --- a/ikuzo/storage/x/elasticsearch8/aggregation_builder_test.go +++ b/ikuzo/storage/x/elasticsearch8/aggregation_builder_test.go @@ -194,8 +194,8 @@ func TestAggregationBuilder_BuildAggregations(t *testing.T) { }, }, { - name: "empty facets returns empty map", - mode: AggFlat, + name: "empty facets returns empty map", + mode: AggFlat, facets: []semantic.FacetRequest{}, want: map[string]any{}, }, diff --git a/ikuzo/storage/x/elasticsearch8/query_builder.go b/ikuzo/storage/x/elasticsearch8/query_builder.go index 21d0425b..7f8f1550 100644 --- a/ikuzo/storage/x/elasticsearch8/query_builder.go +++ b/ikuzo/storage/x/elasticsearch8/query_builder.go @@ -270,7 +270,7 @@ func (qb *QueryBuilder) buildExistsFilter(ef *semantic.ExistsFilter) interface{} return map[string]interface{}{ "nested": map[string]interface{}{ - "path": "resources.entries", + "path": "resources.entries", "query": labelClause, }, } @@ -354,9 +354,9 @@ func (qb *QueryBuilder) buildCollapse(co *semantic.CollapseOptions) map[string]i } return map[string]interface{}{ - "field": translateField(co.Field), - "inner_hits": innerHits, - "max_concurrent_group_requests": 4, + "field": translateField(co.Field), + "inner_hits": innerHits, + "max_concurrent_group_requests": 4, } } diff --git a/ikuzo/storage/x/elasticsearch8/result_parser.go b/ikuzo/storage/x/elasticsearch8/result_parser.go index 391daf4c..b3d5941f 100644 --- a/ikuzo/storage/x/elasticsearch8/result_parser.go +++ b/ikuzo/storage/x/elasticsearch8/result_parser.go @@ -30,10 +30,10 @@ type esTotal struct { // esHit represents a single hit in the search results. type esHit struct { - ID string `json:"_id"` - Score *float64 `json:"_score"` - Source json.RawMessage `json:"_source"` - InnerHits map[string]esInnerHitsWrapper `json:"inner_hits"` + ID string `json:"_id"` + Score *float64 `json:"_score"` + Source json.RawMessage `json:"_source"` + InnerHits map[string]esInnerHitsWrapper `json:"inner_hits"` } // esInnerHitsWrapper wraps inner hits for nested queries. diff --git a/ikuzo/storage/x/elasticsearch8/store.go b/ikuzo/storage/x/elasticsearch8/store.go index 9992d1ad..a6a175b8 100644 --- a/ikuzo/storage/x/elasticsearch8/store.go +++ b/ikuzo/storage/x/elasticsearch8/store.go @@ -17,7 +17,7 @@ import ( // Store implements semantic.SearchStore backed by Elasticsearch 8. type Store struct { - client *Client + client *Client aggMode AggregationMode log zerolog.Logger @@ -188,8 +188,8 @@ func (s *Store) FindSimilar(ctx context.Context, id string, opts *semantic.Simil "like": []map[string]any{ {"_index": indices[0], "_id": id}, }, - "min_term_freq": minTermFreq, - "min_doc_freq": minDocFreq, + "min_term_freq": minTermFreq, + "min_doc_freq": minDocFreq, "max_query_terms": 15, }, }, diff --git a/ikuzo/storage/x/v2adapter/result_translator_test.go b/ikuzo/storage/x/v2adapter/result_translator_test.go index 54ae0517..3908940b 100644 --- a/ikuzo/storage/x/v2adapter/result_translator_test.go +++ b/ikuzo/storage/x/v2adapter/result_translator_test.go @@ -246,9 +246,9 @@ func TestResultTranslator_TranslateItems(t *testing.T) { }, }, }, - wantItems: 1, - wantIDs: []string{"doc456"}, - wantErr: false, + wantItems: 1, + wantIDs: []string{"doc456"}, + wantErr: false, description: "Should handle inline context map", }, { diff --git a/tools/cmd/index_narthex/essync/submitter.go b/tools/cmd/index_narthex/essync/submitter.go index 8366c9ea..665de4dc 100644 --- a/tools/cmd/index_narthex/essync/submitter.go +++ b/tools/cmd/index_narthex/essync/submitter.go @@ -338,7 +338,7 @@ func (w *worker) flush() { successCount++ } else { w.processor.metrics.errors.Value.Add(1) - + // Handle error that can be either a string or an object var errorMsg string switch err := item.Index.Error.(type) { @@ -350,7 +350,7 @@ func (w *worker) flush() { errorMsg = reason } else { // Fall back to JSON representation - errorBytes, _ := json.Marshal(err) + errorBytes, _ := json.Marshal(err) errorMsg = string(errorBytes) // Print the full error object for debugging w.processor.logger.Debug("full error object", "error_details", err) @@ -359,7 +359,7 @@ func (w *worker) flush() { // Fall back to %v format for other cases errorMsg = fmt.Sprintf("%v", err) } - + w.processor.logger.Error("document indexing failed", "status", item.Index.Status, "error", errorMsg) diff --git a/tools/cmd/index_narthex/essync/utils.go b/tools/cmd/index_narthex/essync/utils.go index e86958e2..7ba4c1e2 100644 --- a/tools/cmd/index_narthex/essync/utils.go +++ b/tools/cmd/index_narthex/essync/utils.go @@ -81,22 +81,22 @@ func FindLatestPath(path string, searchStr string) (string, error) { dateStr := parts[0] var date time.Time var err error - + // Try different timestamp formats formats := []string{ - "2006-01-02T15:04:05", // Original format with colons - "2006-01-02T150405", // Format without colons (like yours) - "2006-01-02T15:04", // Format without seconds - "2006-01-02", // Date only + "2006-01-02T15:04:05", // Original format with colons + "2006-01-02T150405", // Format without colons (like yours) + "2006-01-02T15:04", // Format without seconds + "2006-01-02", // Date only } - + for _, format := range formats { date, err = time.Parse(format, dateStr) if err == nil { break } } - + if err != nil { continue } diff --git a/tools/cmd/index_narthex/integration_test.go b/tools/cmd/index_narthex/integration_test.go index 3704f5e6..2c25f474 100644 --- a/tools/cmd/index_narthex/integration_test.go +++ b/tools/cmd/index_narthex/integration_test.go @@ -78,13 +78,13 @@ const testRDF = `dcn_`), - "za": regexp.MustCompile(`za_`), + "dcn": regexp.MustCompile(`dcn_`), + "za": regexp.MustCompile(`za_`), "brabantcloud": regexp.MustCompile(`brabantcloud_`), } - + for _, line := range lines { for aggregator, pattern := range aggregatorPatterns { if pattern.MatchString(line) { @@ -785,7 +784,7 @@ func detectAggregator(lines []string) string { } } } - + return "unknown" } @@ -813,22 +812,22 @@ func detectRDFXML(filePath string) (bool, string, []string, error) { // RDF-XML detection patterns - now requires stricter criteria // Basic RDF indicators (namespace declarations) namespacePatterns := []*regexp.Regexp{ - regexp.MustCompile(`(?i)xmlns:rdf\s*=`), // xmlns:rdf= + regexp.MustCompile(`(?i)xmlns:rdf\s*=`), // xmlns:rdf= regexp.MustCompile(`(?i)http://www\.w3\.org/1999/02/22-rdf-syntax-ns#`), // RDF namespace URI } - + // Strict RDF patterns (actual RDF usage - required for qualification) strictRDFPatterns := []*regexp.Regexp{ - regexp.MustCompile(`(?i)<\s*rdf:RDF`), // 0 { // Check first resource if firstResource, ok := resources[0].(map[string]interface{}); ok { resourceKeys := getMapKeys(firstResource) slog.Debug("First resource", "keys", resourceKeys) - + // Check for context fields examineContextFieldDetailed(firstResource, "context") examineContextFieldDetailed(firstResource, "graphExternalContext") @@ -59,20 +59,20 @@ func examineIndexMessageSource(mesg *domainpb.IndexMessage) { } else { slog.Debug("Resources field not found or not an array") } - + case string: // Source is a string, not expected previewLen := 30 if len(objTyped) < previewLen { previewLen = len(objTyped) } - slog.Error("Source decoded as string, expected object", + slog.Error("Source decoded as string, expected object", "length", len(objTyped), "preview", objTyped[:previewLen]) - + default: // Unexpected type - slog.Error("Source decoded as unexpected type", + slog.Error("Source decoded as unexpected type", "type", fmt.Sprintf("%T", sourceObj)) } } @@ -84,22 +84,22 @@ func examineContextFieldDetailed(resource map[string]interface{}, fieldName stri slog.Debug(fmt.Sprintf("%s field is nil", fieldName)) return } - + switch fieldTyped := field.(type) { case []interface{}: slog.Debug(fmt.Sprintf("%s is array", fieldName), "count", len(fieldTyped)) - + if len(fieldTyped) > 0 { // Examine first item firstItem := fieldTyped[0] - slog.Debug(fmt.Sprintf("First %s item", fieldName), + slog.Debug(fmt.Sprintf("First %s item", fieldName), "type", fmt.Sprintf("%T", firstItem)) - + // If it's a map, look at its keys if itemMap, ok := firstItem.(map[string]interface{}); ok { keys := getMapKeys(itemMap) slog.Debug(fmt.Sprintf("First %s item keys", fieldName), "keys", keys) - + // Check for level field if level, ok := itemMap["Level"]; ok { slog.Debug(fmt.Sprintf("%s has Level field", fieldName), "value", level) @@ -108,9 +108,9 @@ func examineContextFieldDetailed(resource map[string]interface{}, fieldName stri } } } - + default: - slog.Debug(fmt.Sprintf("%s unexpected type", fieldName), + slog.Debug(fmt.Sprintf("%s unexpected type", fieldName), "type", fmt.Sprintf("%T", field)) } -} \ No newline at end of file +} diff --git a/tools/cmd/index_narthex/processdirectory.go b/tools/cmd/index_narthex/processdirectory.go index 57fc9705..a7d9c2f2 100644 --- a/tools/cmd/index_narthex/processdirectory.go +++ b/tools/cmd/index_narthex/processdirectory.go @@ -37,4 +37,4 @@ func processSingleDirectoryWithTagMap(dirPath, targetIndex, customPattern string } return stats, nil -} \ No newline at end of file +} diff --git a/tools/cmd/index_narthex/stats/stats.go b/tools/cmd/index_narthex/stats/stats.go index 6cc6220a..7c7d2079 100644 --- a/tools/cmd/index_narthex/stats/stats.go +++ b/tools/cmd/index_narthex/stats/stats.go @@ -169,7 +169,7 @@ func (pr *ProgressReporter) Update(values []MetricValue) { } } } - + // Write to same line using carriage return fmt.Printf("\r%s", strings.Join(parts, " | ")) } diff --git a/tools/cmd/index_narthex/tagmap.go b/tools/cmd/index_narthex/tagmap.go index 6b88aa8a..8f807a84 100644 --- a/tools/cmd/index_narthex/tagmap.go +++ b/tools/cmd/index_narthex/tagmap.go @@ -48,7 +48,7 @@ func LoadRDFTagMapFromTOML(filePath string) (*index.TagMap, error) { // Create a predicate to tags map predicateToTags := make(map[string][]string) - + // Process each tag type and add to the map for _, uri := range config.RDFTag.Title { addTag(predicateToTags, uri, "title") @@ -108,8 +108,8 @@ func LoadRDFTagMapFromTOML(filePath string) (*index.TagMap, error) { // Create the TagMap from the loaded configuration tagMap := index.NewTagMapFromMap(predicateToTags) - slog.Info("loaded RDF tag map", - "filePath", filePath, + slog.Info("loaded RDF tag map", + "filePath", filePath, "predicates", tagMap.Len()) return tagMap, nil @@ -121,10 +121,10 @@ func addTag(predicateToTags map[string][]string, uri string, tag string) { if uri == "" { return } - + if tags, exists := predicateToTags[uri]; exists { predicateToTags[uri] = append(tags, tag) } else { predicateToTags[uri] = []string{tag} } -} \ No newline at end of file +} diff --git a/tools/cmd/index_narthex/tagmap_test.go b/tools/cmd/index_narthex/tagmap_test.go index d74da0e1..0378ff89 100644 --- a/tools/cmd/index_narthex/tagmap_test.go +++ b/tools/cmd/index_narthex/tagmap_test.go @@ -58,4 +58,4 @@ isoDate = ["https://archief.nl/def/ead/dateiso"] if len(dateRangeTags) != 1 || dateRangeTags[0] != "dateRange" { t.Errorf("Expected dateRange predicate to have tag [dateRange], got %v", dateRangeTags) } -} \ No newline at end of file +}