Skip to content

Commit

Permalink
search: rank MockClient index results by query
Browse files Browse the repository at this point in the history
  • Loading branch information
adamdecaf committed Jan 17, 2025
1 parent e82d0b5 commit b4fe2a6
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 5 deletions.
30 changes: 25 additions & 5 deletions pkg/search/mock_client.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package search

import (
"cmp"
"context"
"slices"
)

type MockClient struct {
Err error

Index []Entity[Value]
Searches []Entity[Value]

SearchResponse SearchResponse
}

var _ Client = (&MockClient{})
Expand All @@ -18,12 +19,31 @@ func NewMockClient() *MockClient {
return &MockClient{}
}

func (c *MockClient) SearchByEntity(ctx context.Context, entity Entity[Value], opts SearchOpts) (SearchResponse, error) {
func (c *MockClient) SearchByEntity(ctx context.Context, query Entity[Value], opts SearchOpts) (SearchResponse, error) {
if c.Err != nil {
return SearchResponse{}, c.Err
}

c.Searches = append(c.Searches, entity)
// Record the search
c.Searches = append(c.Searches, query)

var resp SearchResponse
for _, index := range c.Index {
resp.Entities = append(resp.Entities, SearchedEntity[Value]{
Entity: index,
Match: Similarity(query, index),
})
}

// Sort the results, highest match first
slices.SortFunc(resp.Entities, func(e1, e2 SearchedEntity[Value]) int {
return -1 * cmp.Compare(e1.Match, e2.Match) // invert, make it DESC
})

// Truncate
if len(resp.Entities) > opts.Limit {
resp.Entities = resp.Entities[:opts.Limit]
}

return c.SearchResponse, c.Err
return resp, nil
}
43 changes: 43 additions & 0 deletions pkg/search/mock_client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package search_test

import (
"context"
"testing"

"github.com/moov-io/watchman/pkg/search"

"github.com/stretchr/testify/require"
)

func TestMockClient(t *testing.T) {
ctx := context.Background()
mc := search.NewMockClient()

mc.Index = append(mc.Index, search.Entity[search.Value]{
Name: "Acme corp",
Type: search.EntityBusiness,
})
mc.Index = append(mc.Index, search.Entity[search.Value]{
Name: "Jane Doe",
Type: search.EntityPerson,
})
mc.Index = append(mc.Index, search.Entity[search.Value]{
Name: "Storage Savers",
Type: search.EntityBusiness,
})

query := search.Entity[search.Value]{
Name: "John Doe",
Type: search.EntityPerson,
}
opts := search.SearchOpts{
Limit: 2,
}
resp, err := mc.SearchByEntity(ctx, query, opts)
require.NoError(t, err)
require.Len(t, resp.Entities, 2)

first := resp.Entities[0]
require.Equal(t, "Jane Doe", first.Name)
require.InDelta(t, 0.6667, first.Match, 0.001)
}

0 comments on commit b4fe2a6

Please sign in to comment.