Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
6fafe59
example user + track indexer and search
stereosteve May 16, 2025
763ab88
playlist indexer
stereosteve May 19, 2025
923bac2
autocomplete endpoint
stereosteve May 19, 2025
8a17b7b
wip basic tests
stereosteve May 21, 2025
5f54627
wip: add elastic dsl builder
stereosteve May 21, 2025
028b3c6
es dsl builders for users, tracks, playlists
stereosteve May 22, 2025
a7275fd
Use dsl builders, add searchtest.html
stereosteve May 22, 2025
051156a
socials index to boost items you have interacted with.
stereosteve May 28, 2025
e73d1fa
improve reindex cli. Do all the data.
stereosteve May 29, 2025
a59f911
Merge remote-tracking branch 'origin/main' into sp-es
stereosteve Jun 4, 2025
4215dc8
Merge remote-tracking branch 'origin/main' into sp-es
stereosteve Jun 11, 2025
39ea3b9
Basic search test
stereosteve Jun 11, 2025
9631f08
test various query string filters
stereosteve Jun 12, 2025
ac48ed9
Test that reposted tracks rank higher for current user.
stereosteve Jun 13, 2025
315e98a
more explicit skipAuthCheck flag
stereosteve Jun 16, 2025
85bc659
multi match track search + index tags.
stereosteve Jun 16, 2025
3e5c192
Don't index deleted / private / removed content.
stereosteve Jun 16, 2025
2d05f55
wip: incremental indexing
stereosteve Jun 17, 2025
5778b79
honor kind + only_verified params. Playlist has track stubs
stereosteve Jun 17, 2025
8dc50d6
tag search endpoint
stereosteve Jun 18, 2025
5c3ee61
example of LISTEN for NOTIFY events.
stereosteve Jun 18, 2025
fc40d41
reorganize code... dedicated users / tracks / playlists search endpoints
stereosteve Jun 20, 2025
abb1535
single indexer with collectionConfigs.
stereosteve Jun 21, 2025
e14a474
es-indexer listens to NOTIFY and re-indexes documents.
stereosteve Jun 21, 2025
b57cc64
scoring tweaks
stereosteve Jun 23, 2025
801f3f0
Fix + improve explore pages
stereosteve Jun 23, 2025
a4ab5a9
es-indexer listener batches changes in 10s interval.
stereosteve Jun 24, 2025
e8f95ea
rename v1SearchFull handler func
stereosteve Jun 24, 2025
f772fb8
savings: only personalize results for "full" endpoint
stereosteve Jun 24, 2025
16db5c9
Merge remote-tracking branch 'origin/main' into sp-es
stereosteve Jun 24, 2025
0f0662b
start all containers in github tests
stereosteve Jun 24, 2025
155d665
PR cleanup
stereosteve Jun 25, 2025
dc5ecd5
Merge remote-tracking branch 'origin/main' into sp-es
stereosteve Jun 25, 2025
739a357
rename files: esindexer
stereosteve Jun 25, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
run: docker compose version

- name: Build and run services
run: docker compose up -d db
run: docker compose up -d



Expand Down
14 changes: 6 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,17 @@ test::
sqlc generate
go test -count=1 -cover ./...

staging::
esindexer-staging::
mkdir -p build/staging
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/staging/bridge-amd64
rsync -ravz build/staging/ stage-discovery-4:bridgerton
ssh stage-discovery-4 -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge'
curl 'https://bridgerton.staging.audius.co'
rsync -ravz build/staging/ stage-elasticsearch:bridgerton
ssh stage-elasticsearch -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge'

production::
esindexer-production::
mkdir -p build/production
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/production/bridge-amd64
rsync -ravz build/production/ prod-discovery-4:bridgerton
ssh prod-discovery-4 -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge'
curl 'https://bridgerton.audius.co'
rsync -ravz build/production/ prod-elasticsearch:bridgerton
ssh prod-elasticsearch -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge'

psql::
docker compose exec db psql -U postgres
Expand Down
6 changes: 6 additions & 0 deletions api/auth_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ func (app *ApiServer) recoverAuthorityFromSignatureHeaders(c *fiber.Ctx) string

// Checks if authedWallet is authorized to act on behalf of userId
func (app *ApiServer) isAuthorizedRequest(ctx context.Context, userId int32, authedWallet string) bool {

// tests can opt in to skipAuthCheck
if app.skipAuthCheck {
Comment thread
stereosteve marked this conversation as resolved.
Resolved
return true
}

cacheKey := fmt.Sprintf("%d:%s", userId, authedWallet)
if hit, ok := app.resolveGrantCache.Get(cacheKey); ok {
return hit
Expand Down
7 changes: 5 additions & 2 deletions api/fixture_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
var (
baseRows = map[string]map[string]any{
"users": {
"blocknumber": 101,
"user_id": nil,
"handle": nil,
"handle_lc": nil,
Expand All @@ -29,6 +30,7 @@ var (
"profile_type": nil,
},
"tracks": {
"blocknumber": 101,
"blockhash": "block_abc123",
"track_id": "@track_id",
"is_current": true,
Expand All @@ -54,8 +56,7 @@ var (
"download_conditions": nil,
},
"playlists": {
// "playlist_id": 1,
// "playlist_owner_id": 42,
"blocknumber": 101,
"is_album": false,
"is_private": false,
"playlist_contents": "{}",
Expand All @@ -71,6 +72,8 @@ var (
"playlist_tracks": {
"playlist_id": nil,
"track_id": nil,
"created_at": time.Now(),
"updated_at": time.Now(),
"is_removed": false,
},
"follows": {
Expand Down
89 changes: 89 additions & 0 deletions api/searchv1/dsl_helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package searchv1

import (
"context"
"encoding/json"
"fmt"
"io"
"strings"

"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
"github.com/tidwall/gjson"
Comment thread
stereosteve marked this conversation as resolved.
Resolved
"github.com/tidwall/pretty"
)

func toAnySlice[T any](slice []T) []any {
result := make([]any, len(slice))
for i, v := range slice {
result[i] = v
}
return result
}

func BuildFunctionScoreDSL(scoreField string, innerQuery map[string]any) string {
innerJson, err := json.Marshal(innerQuery)
if err != nil {
panic(err)
}

dsl := fmt.Sprintf(`
{
"query": {
"function_score": {
"query": %s,
"boost_mode": "multiply",
"score_mode": "multiply",
"functions": [
{
"field_value_factor": {
"field": %q,
"factor": 100,
"modifier": "ln2p",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why the ln2p?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because the python codebase used it. It adds 2 to the value to smooths out the lower end of the range a bit...

"missing": 0
}
}
]
}
}
}`, innerJson, scoreField)

return dsl
}

func SearchAndPluck(esClient *elasticsearch.Client, index, dsl string, limit, offset int) ([]int32, error) {
req := esapi.SearchRequest{
Index: []string{index},
Body: strings.NewReader(dsl),
Source: []string{"false"},
Size: &limit,
From: &offset,
}

res, err := req.Do(context.Background(), esClient)
if err != nil {
return nil, err
}
defer res.Body.Close()

if res.IsError() {
return nil, fmt.Errorf("Search %s failed: %s", index, res.String())
}

body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}

result := []int32{}
for _, hit := range gjson.GetBytes(body, "hits.hits").Array() {
id := hit.Get("_id").Int()
result = append(result, int32(id))
}

return result, nil
}

func pprintJson(j string) {
fmt.Println(string(pretty.Pretty([]byte(j))))
}
73 changes: 73 additions & 0 deletions api/searchv1/playlist_search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package searchv1

import (
"fmt"

"github.com/aquasecurity/esquery"
)

type PlaylistSearchQuery struct {
Query string
Genres []string
Moods []string
IsTagSearch bool
IsAlbum bool
OnlyVerified bool
MyID int32
}

func (q *PlaylistSearchQuery) Map() map[string]any {
builder := esquery.Bool()

if q.IsTagSearch {
builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tracks.tags").Type(esquery.MatchTypeBoolPrefix))
} else if q.Query != "" {
builder.Must(esquery.MultiMatch().Query(q.Query).Fields("title^10", "user.handle", "user.name", "tracks.tags").Type(esquery.MatchTypeBoolPrefix))
} else {
builder.Must(esquery.MatchAll())
}

builder.Filter(esquery.Term("is_album", q.IsAlbum))

if len(q.Genres) > 0 {
builder.Filter(esquery.Terms("tracks.genre.keyword", toAnySlice(q.Genres)...))
// by using a match query... the TF/IDF will apply to tracks. Which will rank playlists higher if they have a larger proportion of genre
for _, value := range q.Genres {
builder.Should(esquery.Match("tracks.genre", value)).Boost(10)
}
}

if len(q.Moods) > 0 {
builder.Filter(esquery.Terms("tracks.mood.keyword", toAnySlice(q.Moods)...))
// by using a match query... the TF/IDF will apply to tracks. Which will rank playlists higher if they have a larger proportion of mood
for _, value := range q.Genres {
builder.Should(esquery.Match("tracks.mood", value)).Boost(10)
}
}

if q.OnlyVerified {
builder.Must(esquery.Term("tracks.user.is_verified", true))
} else {
builder.Should(esquery.Term("user.is_verified", true))
}

// personalize results
if q.MyID > 0 {
builder.Should(esquery.CustomQuery(map[string]any{
"terms": map[string]any{
"_id": map[string]any{
"index": "socials",
"id": fmt.Sprintf("%d", q.MyID),
"path": "reposted_playlist_ids",
},
"boost": 10,
},
}))
}

return builder.Map()
}

func (q *PlaylistSearchQuery) DSL() string {
return BuildFunctionScoreDSL("repost_count", q.Map())
}
109 changes: 109 additions & 0 deletions api/searchv1/track_search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package searchv1

import (
"fmt"

"github.com/aquasecurity/esquery"
)

type TrackSearchQuery struct {
Query string
MinBPM int
MaxBPM int
IsDownloadable bool
IsPurchaseable bool
IsTagSearch bool
OnlyVerified bool
Genres []string
Moods []string
MusicalKeys []string
MyID int32
}

func (q *TrackSearchQuery) Map() map[string]any {
builder := esquery.Bool()

if q.IsTagSearch {
builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tags").Type(esquery.MatchTypeBoolPrefix))
} else if q.Query != "" {
builder.Must(
esquery.MultiMatch().
Query(q.Query).
Fields("title^10", "user.handle", "user.name", "tags").
// Operator(esquery.OperatorAnd).
Type(esquery.MatchTypeBoolPrefix),
)

// for exact title / handle / artist name match
builder.Should(
esquery.MultiMatch().Query(q.Query).Fields("title", "user.name", "user.handle").Operator(esquery.OperatorAnd).Type(esquery.MatchTypePhrasePrefix),
)
} else {
builder.Must(esquery.MatchAll())
}

if q.MinBPM > 0 || q.MaxBPM > 0 {
bpmRange := esquery.Range("bpm")
if q.MinBPM > 0 {
bpmRange.Gte(q.MinBPM)
}
if q.MaxBPM > 0 {
bpmRange.Lte(q.MaxBPM)
}
builder.Filter(bpmRange)
}

if len(q.Genres) > 0 {
builder.Filter(esquery.Terms("genre.keyword", toAnySlice(q.Genres)...))
}

if len(q.Moods) > 0 {
builder.Filter(esquery.Terms("mood.keyword", toAnySlice(q.Moods)...))
}

if len(q.MusicalKeys) > 0 {
builder.Filter(esquery.Terms("musical_key.keyword", toAnySlice(q.MusicalKeys)...))
}

if q.IsDownloadable {
builder.Filter(esquery.Term("is_downloadable", true))
}

// todo: only_with_downloads
// => downloadable + has stems

if q.IsPurchaseable {
// stream or download
builder.Filter(
esquery.Bool().
Should(esquery.Exists("stream_conditions.usdc_purchase")).
Should(esquery.Exists("download_conditions.usdc_purchase")),
)
}

if q.OnlyVerified {
builder.Must(esquery.Term("user.is_verified", true))
} else {
builder.Should(esquery.Term("user.is_verified", true))
}

// boost tracks that are saved / reposted
if q.MyID > 0 {
builder.Should(esquery.CustomQuery(map[string]any{
"terms": map[string]any{
"_id": map[string]any{
"index": "socials",
"id": fmt.Sprintf("%d", q.MyID),
"path": "reposted_track_ids",
},
"boost": 10,
},
}))
}

return builder.Map()
}

func (q *TrackSearchQuery) DSL() string {
return BuildFunctionScoreDSL("repost_count", q.Map())
}
Loading