From 6fafe59744f35a0705f08c820768d5f214c457c0 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Fri, 16 May 2025 17:05:23 -0400 Subject: [PATCH 01/30] example user + track indexer and search --- go.mod | 4 +- go.sum | 175 +++++--------------------------------- main.go | 12 +++ searcher/base_indexer.go | 99 +++++++++++++++++++++ searcher/demo.go | 70 +++++++++++++++ searcher/track_indexer.go | 101 ++++++++++++++++++++++ searcher/user_indexer.go | 117 +++++++++++++++++++++++++ 7 files changed, 421 insertions(+), 157 deletions(-) create mode 100644 searcher/base_indexer.go create mode 100644 searcher/demo.go create mode 100644 searcher/track_indexer.go create mode 100644 searcher/user_indexer.go diff --git a/go.mod b/go.mod index 160da27f..e31ed6e5 100644 --- a/go.mod +++ b/go.mod @@ -5,12 +5,12 @@ go 1.24.1 require ( github.com/AudiusProject/audiusd v0.0.0-20250423205417-9adf00a64112 github.com/axiomhq/axiom-go v0.23.0 + github.com/elastic/go-elasticsearch/v8 v8.18.0 github.com/ethereum/go-ethereum v1.15.8 github.com/gagliardetto/binary v0.8.0 github.com/gagliardetto/solana-go v1.12.1-0.20250314202648-ca3f5f643435 github.com/gofiber/contrib/fiberzap/v2 v2.1.5 github.com/gofiber/fiber/v2 v2.52.6 - github.com/jackc/pgtype v1.14.4 github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f github.com/jackc/pgx/v5 v5.7.4 github.com/joho/godotenv v1.5.1 @@ -53,6 +53,7 @@ require ( github.com/dgraph-io/ristretto/v2 v2.1.0 // indirect github.com/dolthub/maphash v0.1.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect + github.com/elastic/elastic-transport-go/v8 v8.7.0 // indirect github.com/fatih/color v1.18.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/gagliardetto/treeout v0.1.4 // indirect @@ -84,7 +85,6 @@ require ( github.com/gorilla/websocket v1.5.3 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect github.com/holiman/uint256 v1.3.2 // indirect - github.com/jackc/pgio v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect diff --git a/go.sum b/go.sum index 847645c4..62c88238 100644 --- a/go.sum +++ b/go.sum @@ -8,7 +8,6 @@ github.com/AudiusProject/audiusd v0.0.0-20250423205417-9adf00a64112/go.mod h1:DD github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/DataDog/zstd v1.5.2 h1:vUG4lAyuPCXO0TLbXvPv7EB7cNK1QV/luu55UHLrrn8= github.com/DataDog/zstd v1.5.2/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= -github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 h1:MzBOUgng9orim59UnfUTLRjMpd09C5uEVQ6RPGeCaVI= github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129/go.mod h1:rFgpPQZYZ8vdbc+48xibu8ALc3yeyd64IhHS+PU6Yyg= github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= @@ -33,7 +32,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= +github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4= +github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I= github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8= github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4= @@ -52,11 +52,8 @@ github.com/cometbft/cometbft-db v1.0.1 h1:SylKuLseMLQKw3+i8y8KozZyJcQSL98qEe2CGM github.com/cometbft/cometbft-db v1.0.1/go.mod h1:EBrFs1GDRiTqrWXYi4v90Awf/gcdD5ExzdPbg4X8+mk= github.com/cometbft/cometbft/api v1.0.0 h1:gGBwvsJi/gnHJEtwYfjPIGs2AKg/Vfa1ZuKCPD1/Ko4= github.com/cometbft/cometbft/api v1.0.0/go.mod h1:EkQiqVSu/p2ebrZEnB2z6Re7r8XNe//M7ylR0qEwWm0= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/cosmos/gogoproto v1.7.0 h1:79USr0oyXAbxg3rspGh/m4SWNyoz/GLaAh0QlCe2fro= github.com/cosmos/gogoproto v1.7.0/go.mod h1:yWChEv5IUEYURQasfyBW5ffkMHR/90hiHgbNgrtp4j0= -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -70,10 +67,16 @@ github.com/dgraph-io/badger/v4 v4.5.1 h1:7DCIXrQjo1LKmM96YD+hLVJ2EEsyyoWxJfpdd56 github.com/dgraph-io/badger/v4 v4.5.1/go.mod h1:qn3Be0j3TfV4kPbVoK0arXCD1/nr1ftth6sbL5jxdoA= github.com/dgraph-io/ristretto/v2 v2.1.0 h1:59LjpOJLNDULHh8MC4UaegN52lC4JnO2dITsie/Pa8I= github.com/dgraph-io/ristretto/v2 v2.1.0/go.mod h1:uejeqfYXpUomfse0+lO+13ATz4TypQYLJZzBSAemuB4= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dolthub/maphash v0.1.0 h1:bsQ7JsF4FkkWyrP3oCnFJgrCUAFbFf3kOl4L/QxPDyQ= github.com/dolthub/maphash v0.1.0/go.mod h1:gkg4Ch4CdCDu5h6PMriVLawB7koZ+5ijb9puGMV50a4= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/elastic/elastic-transport-go/v8 v8.7.0 h1:OgTneVuXP2uip4BA658Xi6Hfw+PeIOod2rY3GVMGoVE= +github.com/elastic/elastic-transport-go/v8 v8.7.0/go.mod h1:YLHer5cj0csTzNFXoNQ8qhtGY1GTvSqPnKWKaqQE3Hk= +github.com/elastic/go-elasticsearch/v8 v8.18.0 h1:ANNq1h7DEiPUaALb8+5w3baQzaS08WfHV0DNzp0VG4M= +github.com/elastic/go-elasticsearch/v8 v8.18.0/go.mod h1:WLqwXsJmQoYkoA9JBFeEwPkQhCfAZuUvfpdU/NvSSf0= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= @@ -84,12 +87,14 @@ github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/gagliardetto/binary v0.8.0 h1:U9ahc45v9HW0d15LoN++vIXSJyqR/pWw8DDlhd7zvxg= github.com/gagliardetto/binary v0.8.0/go.mod h1:2tfj51g5o9dnvsc+fL3Jxr22MuWzYXwx9wEoN0XQ7/c= -github.com/gagliardetto/solana-go v1.12.0 h1:rzsbilDPj6p+/DOPXBMLhwMZeBgeRuXjm5zQFCoXgsg= -github.com/gagliardetto/solana-go v1.12.0/go.mod h1:l/qqqIN6qJJPtxW/G1PF4JtcE3Zg2vD2EliZrr9Gn5k= github.com/gagliardetto/solana-go v1.12.1-0.20250314202648-ca3f5f643435 h1:Ju6/BZbQ0aYVZggNJlyov8X9VIE7pbzTnU9uF9ffin4= github.com/gagliardetto/solana-go v1.12.1-0.20250314202648-ca3f5f643435/go.mod h1:l/qqqIN6qJJPtxW/G1PF4JtcE3Zg2vD2EliZrr9Gn5k= github.com/gagliardetto/treeout v0.1.4 h1:ozeYerrLCmCubo1TcIjFiOWTTGteOOHND1twdFpgwaw= @@ -98,10 +103,10 @@ github.com/gammazero/deque v1.0.0 h1:LTmimT8H7bXkkCy6gZX7zNLtkbz4NdS2z8LZuor3j34 github.com/gammazero/deque v1.0.0/go.mod h1:iflpYvtGfM3U8S8j+sZEKIak3SAKYpA5/SQewgfXDKo= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= -github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -127,12 +132,10 @@ github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+Gr github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/gofiber/contrib/fiberzap/v2 v2.1.5 h1:mJnuTFd1gQw/DFUz1mkJlMmiwPGJ5cEfjuOxYugKmT4= github.com/gofiber/contrib/fiberzap/v2 v2.1.5/go.mod h1:PtrHZhZvHC8deg3jRfjzlv1tk3Mtn0cmat7db+eqA6I= github.com/gofiber/fiber/v2 v2.52.6 h1:Rfp+ILPiYSvvVuIPvxrBns+HJp8qGLDnLJawAu27XVI= github.com/gofiber/fiber/v2 v2.52.6/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw= -github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= @@ -171,7 +174,6 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -184,61 +186,14 @@ github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1ns github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA= github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/jackc/chunkreader v1.0.0 h1:4s39bBR8ByfqH+DKm8rQA3E1LHZWB9XWcrz8fqaZbe0= -github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= -github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= -github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA= -github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE= -github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s= -github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o= -github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY= -github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI= -github.com/jackc/pgconn v1.14.3 h1:bVoTr12EGANZz66nZPkMInAV/KHD2TxH9npjXXgiB3w= -github.com/jackc/pgconn v1.14.3/go.mod h1:RZbme4uasqzybK2RK5c65VsHxoyaml09lx3tXOcO/VM= -github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= -github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= -github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE= -github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgproto3 v1.1.0 h1:FYYE4yRw+AgI8wXIinMlNjBbp/UitDJwfj5LqqewP1A= -github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78= -github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA= -github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg= -github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= -github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= -github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUOag= -github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= -github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg= -github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc= -github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw= -github.com/jackc/pgtype v1.8.1-0.20210724151600-32e20a603178/go.mod h1:C516IlIV9NKqfsMCXTdChteoXmwgUceqaLfjg2e3NlM= -github.com/jackc/pgtype v1.14.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4= -github.com/jackc/pgtype v1.14.4 h1:fKuNiCumbKTAIxQwXfB/nsrnkEI6bPJrrSiMKgbJ2j8= -github.com/jackc/pgtype v1.14.4/go.mod h1:aKeozOde08iifGosdJpz9MBZonJOUJxqNpPBcMJTlVA= github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f h1:ahoGnXfh4wiCisojvzq1PzgxzFwJEUHMI26pUY6oluk= github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f/go.mod h1:m9tCxmy1PSUQa5o0aL4rQTowmJD1BK2Zc7dgnK/IrXc= -github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y= -github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM= -github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc= -github.com/jackc/pgx/v4 v4.12.1-0.20210724153913-640aa07df17c/go.mod h1:1QD0+tgSXP7iUjYm9C1NxKhny7lq6ee99u/z+IHFcgs= -github.com/jackc/pgx/v4 v4.18.2 h1:xVpYkNR5pk5bMCZGfClbO962UIqVABcAGt7ha1s/FeU= -github.com/jackc/pgx/v4 v4.18.2/go.mod h1:Ey4Oru5tH5sB6tV7hDmfWFahwF15Eb7DNXlRKx2CkVw= github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= -github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v1.3.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= @@ -254,36 +209,22 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o github.com/klauspost/compress v1.11.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= -github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/linxGnu/grocksdb v1.9.3 h1:s1cbPcOd0cU2SKXRG1nEqCOWYAELQjdqg3RVI2MH9ik= github.com/linxGnu/grocksdb v1.9.3/go.mod h1:QYiYypR2d4v63Wj1adOOfzglnoII0gLj3PNh4fZkcFA= github.com/logrusorgru/aurora v2.0.3+incompatible h1:tOpm7WcpBTn4fjmVfgpQq0EfczGlG91VSDkswnjF5A8= github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= -github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= @@ -306,12 +247,15 @@ github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjW github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a h1:dlRvE5fWabOchtH7znfiFCcOvmIYgOeAS5ifBXBlh9Q= github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a/go.mod h1:hVoHR2EVESiICEMbg137etN/Lx+lSrHPTD39Z/uE+2s= github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= @@ -319,6 +263,8 @@ github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= github.com/petermattis/goid v0.0.0-20250319124200-ccd6737f222a h1:S+AGcmAESQ0pXCUNnRH7V+bOUIgkSX5qVt2cNKCrm0Q= github.com/petermattis/goid v0.0.0-20250319124200-ccd6737f222a/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -338,39 +284,25 @@ github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoG github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= -github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= -github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= github.com/segmentio/encoding v0.4.1 h1:KLGaLSW0jrmhB58Nn4+98spfvPvmo4Ci1P/WIQ9wn7w= github.com/segmentio/encoding v0.4.1/go.mod h1:/d03Cd8PoaDeceuhUUUQWjU0KhWjrmYrWPgtJHYZSnI= -github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= -github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/speps/go-hashids/v2 v2.0.1 h1:ViWOEqWES/pdOSq+C1SLVa8/Tnsd52XC34RY7lt7m4g= github.com/speps/go-hashids/v2 v2.0.1/go.mod h1:47LKunwvDZki/uRVD6NImtyk712yFzIs3UF3KlHohGw= github.com/streamingfast/logging v0.0.0-20230608130331-f22c91403091 h1:RN5mrigyirb8anBEtdjtHFIufXdacyTi6i4KBfeNXeo= github.com/streamingfast/logging v0.0.0-20230608130331-f22c91403091/go.mod h1:VlduQ80JcGJSargkRU4Sg9Xo63wZD/l8A5NC/Uo1/uU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -402,8 +334,6 @@ github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3i github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 h1:qxen9oVGzDdIRP6ejyAJc760RwW4SnVDiTYTzwnXuxo= go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5/go.mod h1:eW0HG9/oHQhvRCvb1/pIXW4cOvtDqeQK+XSi3TnwaXY= go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80= @@ -430,10 +360,7 @@ go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4= go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4= -go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= @@ -441,33 +368,19 @@ go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= -go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/ratelimit v0.2.0 h1:UQE2Bgi7p2B85uP5dC2bbRtig0C+OeNRnNEafLjsLPA= go.uber.org/ratelimit v0.2.0/go.mod h1:YYBV4e4naJvhpitQrWJu1vCpgB7CboMe0qhltKt6mUg= -go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= -go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.20.0/go.mod h1:Xwo95rrVNIoSMx9wa1JroENMToLWn3RNVrTBpLHgZPQ= golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -477,13 +390,9 @@ golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTk golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -491,19 +400,13 @@ golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -513,25 +416,15 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -541,31 +434,16 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o= golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= @@ -574,21 +452,11 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -626,11 +494,9 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -642,4 +508,3 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= diff --git a/main.go b/main.go index eba2406e..f9c2e584 100644 --- a/main.go +++ b/main.go @@ -1,11 +1,23 @@ package main import ( + "fmt" + "os" + "bridgerton.audius.co/api" "bridgerton.audius.co/config" + "bridgerton.audius.co/searcher" ) func main() { + + if len(os.Args) > 1 && os.Args[1] == "search" { + fmt.Println("search time...") + searcher.Demo() + return + } + as := api.NewApiServer(config.Cfg) as.Serve() + } diff --git a/searcher/base_indexer.go b/searcher/base_indexer.go new file mode 100644 index 00000000..74c8f6a8 --- /dev/null +++ b/searcher/base_indexer.go @@ -0,0 +1,99 @@ +package searcher + +import ( + "context" + "fmt" + "log" + "strings" + + "github.com/elastic/go-elasticsearch/v8" + "github.com/elastic/go-elasticsearch/v8/esutil" + "github.com/jackc/pgx/v5/pgxpool" +) + +type BaseIndexer struct { + pool *pgxpool.Pool + esc *elasticsearch.Client +} + +func (base *BaseIndexer) createIndex(indexName string, mapping string, drop bool) error { + if drop { + _, err := base.esc.Indices.Delete([]string{indexName}) + if err != nil { + fmt.Println("drop error", indexName, err) + } + } + + res, err := base.esc.Indices.Create( + indexName, + base.esc.Indices.Create.WithBody( + strings.NewReader(mapping), + ), + ) + if err != nil { + fmt.Println("create index error", indexName, err) + return err + } + + fmt.Println("created index", indexName) + return res.Body.Close() +} + +func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { + ctx := context.Background() + bulk, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{ + Index: index, + Client: base.esc, + NumWorkers: 2, + Refresh: "true", + }) + if err != nil { + log.Fatalf("Error creating the indexer: %s", err) + } + + rows, err := base.pool.Query(ctx, sql) + if err != nil { + return err + } + defer rows.Close() + + for rows.Next() { + var id int + var doc string + if err := rows.Scan(&id, &doc); err != nil { + fmt.Println("row scan error:", err) + continue + } + + err = bulk.Add(ctx, esutil.BulkIndexerItem{ + Action: "index", + DocumentID: fmt.Sprintf("%d", id), + Body: strings.NewReader(doc), + OnSuccess: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem) { + fmt.Println("index", id, doc) + }, + OnFailure: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem, err error) { + if err != nil { + log.Printf("ERROR: %s", err) + } else { + log.Printf("ERROR: %s: %s", res.Error.Type, res.Error.Reason) + } + }, + }) + + if err != nil { + fmt.Println("es index error:", err) + continue + } + } + + if err := rows.Err(); err != nil { + fmt.Println("rows error:", err) + } + + if err := bulk.Close(context.Background()); err != nil { + log.Fatalf("Unexpected error: %s", err) + } + + return nil +} diff --git a/searcher/demo.go b/searcher/demo.go new file mode 100644 index 00000000..fd717185 --- /dev/null +++ b/searcher/demo.go @@ -0,0 +1,70 @@ +package searcher + +import ( + "context" + "log" + + "bridgerton.audius.co/config" + "github.com/elastic/go-elasticsearch/v8" + "github.com/jackc/pgx/v5/pgxpool" +) + +func mustDialPostgres() *pgxpool.Pool { + connConfig, err := pgxpool.ParseConfig(config.Cfg.DbUrl) + if err != nil { + panic(err) + } + + pool, err := pgxpool.NewWithConfig(context.Background(), connConfig) + if err != nil { + panic(err) + } + return pool +} + +func mustDialElasticsearch() *elasticsearch.Client { + cfg := elasticsearch.Config{ + Addresses: []string{ + "http://35.238.44.255:21302", + }, + } + + esc, err := elasticsearch.NewClient(cfg) + if err != nil { + log.Fatalf("Error creating the client: %s", err) + } + + return esc +} + +func Demo() { + pool := mustDialPostgres() + esc := mustDialElasticsearch() + + baseIndexer := &BaseIndexer{ + pool, + esc, + } + + userIndexer := &UserIndexer{baseIndexer} + + if err := userIndexer.createIndex(true); err != nil { + panic(err) + } + if err := userIndexer.indexAll(); err != nil { + panic(err) + } + + userIndexer.search("ray") + + trackIndexer := &TrackIndexer{baseIndexer} + + if err := trackIndexer.createIndex(true); err != nil { + panic(err) + } + if err := trackIndexer.indexAll(); err != nil { + panic(err) + } + + trackIndexer.search("rap") +} diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go new file mode 100644 index 00000000..cbe06d51 --- /dev/null +++ b/searcher/track_indexer.go @@ -0,0 +1,101 @@ +package searcher + +import ( + "encoding/json" + "fmt" + "strings" +) + +type TrackIndexer struct { + *BaseIndexer +} + +func (ti *TrackIndexer) createIndex(drop bool) error { + // we rely on elasticsearch dynamic mapping + // so we only need to specify properties that might be ambigious (int vs float) + mapping := `{ + "mappings": { + "properties": { + "bpm": { "type": "float" } + } + } + }` + return ti.BaseIndexer.createIndex("tracks", mapping, drop) +} + +func (ti *TrackIndexer) indexAll() error { + sql := ` + SELECT + track_id, + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'duration', duration, + 'saveCount', aggregate_track.save_count, + 'repostCount', aggregate_track.repost_count, + 'commentCount', aggregate_track.comment_count, + 'releaseDate', coalesce(release_date, tracks.created_at), + 'musicalKey', musical_key, + 'bpm', bpm, + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'followerCount', aggregate_user.follower_count + ) + ) + FROM tracks + JOIN aggregate_track USING (track_id) + JOIN users ON owner_id = user_id + JOIN aggregate_user USING (user_id) + LIMIT 10000` + + return ti.bulkIndexQuery("tracks", sql) +} + +func (ti *TrackIndexer) search(q string) { + query := fmt.Sprintf(`{ + "query": { + "multi_match": { + "query": %q, + "fields": ["title", "genre", "mood"] + } + } + }`, q) + + fmt.Println(query) + + res, err := ti.esc.Search( + ti.esc.Search.WithIndex("tracks"), + ti.esc.Search.WithBody(strings.NewReader(query)), + ) + if err != nil { + fmt.Println("es search error:", err) + return + } + defer res.Body.Close() + + type hit struct { + ID string `json:"_id"` + } + type hits struct { + Hits struct { + Hits []hit `json:"hits"` + } `json:"hits"` + } + + var result hits + if err := json.NewDecoder(res.Body).Decode(&result); err != nil { + fmt.Println("decode error:", err) + return + } + + var ids []string + for _, h := range result.Hits.Hits { + ids = append(ids, h.ID) + } + + fmt.Println("found ids:", ids) + +} diff --git a/searcher/user_indexer.go b/searcher/user_indexer.go new file mode 100644 index 00000000..3e2fbde9 --- /dev/null +++ b/searcher/user_indexer.go @@ -0,0 +1,117 @@ +package searcher + +import ( + "context" + "encoding/json" + "fmt" + "log" + "strings" + + "github.com/elastic/go-elasticsearch/v8/esapi" +) + +/* + +stage: +http://35.239.100.60:21302 + +prod: +http://35.238.44.255:21302 + +*/ + +type UserIndexer struct { + *BaseIndexer +} + +func (ui *UserIndexer) createIndex(drop bool) error { + + mapping := `{ + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "handle": { + "type": "text" + }, + "location": { + "type": "text" + }, + "follower_count": { + "type": "integer" + }, + "track_count": { + "type": "integer" + } + } + } + }` + + return ui.BaseIndexer.createIndex("users", mapping, drop) +} + +func (ui *UserIndexer) indexAll() error { + sql := ` + SELECT + user_id, + json_build_object( + 'name', name, + 'handle', handle, + 'bio', bio, + 'location', location, + 'created_at', created_at, + + 'track_count', track_count, + 'playlist_count', playlist_count, + 'follower_count', follower_count, + 'repost_count', repost_count, + 'track_save_count', track_save_count, + 'supporter_count', supporter_count, + 'supporting_count', supporting_count, + 'dominant_genre', dominant_genre, + 'dominant_genre_count', dominant_genre_count + ) + FROM users + JOIN aggregate_user USING (user_id) + LIMIT 10000` + + return ui.bulkIndexQuery("users", sql) +} + +func (ui *UserIndexer) search(q string) { + query := fmt.Sprintf(`{ + "query": { + "simple_query_string": { + "query": %q, + "default_operator": "AND" + } + } + }`, q+"*") + + req := esapi.SearchRequest{ + Index: []string{"users"}, + Body: strings.NewReader(query), + } + + res, err := req.Do(context.Background(), ui.esc) + if err != nil { + log.Fatalf("Error getting response: %s", err) + } + defer res.Body.Close() + + if res.IsError() { + log.Fatalf("Error: %s", res.String()) + } + + // Print the response body + var r map[string]interface{} + if err := json.NewDecoder(res.Body).Decode(&r); err != nil { + log.Fatalf("Error parsing the response body: %s", err) + } + + // Print the search results + for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) { + fmt.Printf("Document: %v\n", hit) + } +} From 763ab8840318deb3006c6af48ce9430e5fdb1702 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Mon, 19 May 2025 10:38:20 -0400 Subject: [PATCH 02/30] playlist indexer --- searcher/demo.go | 48 ++++++++++++------ searcher/playlist_indexer.go | 98 ++++++++++++++++++++++++++++++++++++ searcher/track_indexer.go | 12 ++--- 3 files changed, 138 insertions(+), 20 deletions(-) create mode 100644 searcher/playlist_indexer.go diff --git a/searcher/demo.go b/searcher/demo.go index fd717185..22766545 100644 --- a/searcher/demo.go +++ b/searcher/demo.go @@ -37,34 +37,54 @@ func mustDialElasticsearch() *elasticsearch.Client { return esc } -func Demo() { - pool := mustDialPostgres() - esc := mustDialElasticsearch() +func playlistDemo(base *BaseIndexer) { + i := &PlaylistIndexer{base} - baseIndexer := &BaseIndexer{ - pool, - esc, + if err := i.createIndex(true); err != nil { + panic(err) + } + if err := i.indexAll(); err != nil { + panic(err) } - userIndexer := &UserIndexer{baseIndexer} + i.search("ray") +} + +func userDemo(base *BaseIndexer) { + i := &UserIndexer{base} - if err := userIndexer.createIndex(true); err != nil { + if err := i.createIndex(true); err != nil { panic(err) } - if err := userIndexer.indexAll(); err != nil { + if err := i.indexAll(); err != nil { panic(err) } - userIndexer.search("ray") + i.search("ray") +} - trackIndexer := &TrackIndexer{baseIndexer} +func trackDemo(base *BaseIndexer) { + i := &TrackIndexer{base} - if err := trackIndexer.createIndex(true); err != nil { + if err := i.createIndex(true); err != nil { panic(err) } - if err := trackIndexer.indexAll(); err != nil { + if err := i.indexAll(); err != nil { panic(err) } - trackIndexer.search("rap") + i.search("rap") +} + +func Demo() { + pool := mustDialPostgres() + esc := mustDialElasticsearch() + + baseIndexer := &BaseIndexer{ + pool, + esc, + } + + // playlistDemo(baseIndexer) + trackDemo(baseIndexer) } diff --git a/searcher/playlist_indexer.go b/searcher/playlist_indexer.go new file mode 100644 index 00000000..71d89eed --- /dev/null +++ b/searcher/playlist_indexer.go @@ -0,0 +1,98 @@ +package searcher + +import ( + "encoding/json" + "fmt" + "strings" +) + +type PlaylistIndexer struct { + *BaseIndexer +} + +func (pi *PlaylistIndexer) createIndex(drop bool) error { + // Specify mappings for playlist index + // Only specifying properties that might be ambiguous + mapping := `{ + "mappings": { + "properties": { + } + } + }` + return pi.BaseIndexer.createIndex("playlists", mapping, drop) +} + +func (pi *PlaylistIndexer) indexAll() error { + sql := ` + SELECT + playlist_id, + json_build_object( + 'title', playlist_name, + 'description', description, + 'track_count', track_count, + 'save_count', aggregate_playlist.save_count, + 'repost_count', aggregate_playlist.repost_count, + 'last_updated', playlists.updated_at, + 'created_at', playlists.created_at, + 'is_private', is_private, + 'is_album', playlists.is_album, + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'follower_count', aggregate_user.follower_count + ) + ) + FROM playlists + JOIN aggregate_playlist USING (playlist_id) + JOIN users ON playlist_owner_id = user_id + JOIN aggregate_user USING (user_id) + LIMIT 10000` + + return pi.bulkIndexQuery("playlists", sql) +} + +func (pi *PlaylistIndexer) search(q string) { + query := fmt.Sprintf(`{ + "query": { + "multi_match": { + "query": %q, + "fields": ["title", "description"] + } + } + }`, q) + + fmt.Println(query) + + res, err := pi.esc.Search( + pi.esc.Search.WithIndex("playlists"), + pi.esc.Search.WithBody(strings.NewReader(query)), + ) + if err != nil { + fmt.Println("es search error:", err) + return + } + defer res.Body.Close() + + type hit struct { + ID string `json:"_id"` + } + type hits struct { + Hits struct { + Hits []hit `json:"hits"` + } `json:"hits"` + } + + var result hits + if err := json.NewDecoder(res.Body).Decode(&result); err != nil { + fmt.Println("decode error:", err) + return + } + + var ids []string + for _, h := range result.Hits.Hits { + ids = append(ids, h.ID) + } + + fmt.Println("found ids:", ids) +} diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go index cbe06d51..cf511311 100644 --- a/searcher/track_indexer.go +++ b/searcher/track_indexer.go @@ -32,17 +32,17 @@ func (ti *TrackIndexer) indexAll() error { 'genre', genre, 'mood', mood, 'duration', duration, - 'saveCount', aggregate_track.save_count, - 'repostCount', aggregate_track.repost_count, - 'commentCount', aggregate_track.comment_count, - 'releaseDate', coalesce(release_date, tracks.created_at), - 'musicalKey', musical_key, + 'save_count', aggregate_track.save_count, + 'repost_count', aggregate_track.repost_count, + 'comment_count', aggregate_track.comment_count, + 'release_date', coalesce(release_date, tracks.created_at), + 'musical_key', musical_key, 'bpm', bpm, 'user', json_build_object( 'handle', users.handle, 'name', users.name, 'location', users.location, - 'followerCount', aggregate_user.follower_count + 'follower_count', aggregate_user.follower_count ) ) FROM tracks From 923bac27e47c518a6fba4eaa265c072a1287c6a0 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Mon, 19 May 2025 12:07:51 -0400 Subject: [PATCH 03/30] autocomplete endpoint --- api/server.go | 12 ++++ api/v1_search_autocomplete.go | 117 ++++++++++++++++++++++++++++++++++ searcher/conn.go | 13 ++++ searcher/demo.go | 9 +-- searcher/search_and_pluck.go | 42 ++++++++++++ 5 files changed, 185 insertions(+), 8 deletions(-) create mode 100644 api/v1_search_autocomplete.go create mode 100644 searcher/conn.go create mode 100644 searcher/search_and_pluck.go diff --git a/api/server.go b/api/server.go index 2718cef0..368f44e2 100644 --- a/api/server.go +++ b/api/server.go @@ -12,10 +12,12 @@ import ( "bridgerton.audius.co/api/spl" "bridgerton.audius.co/api/spl/programs/reward_manager" "bridgerton.audius.co/config" + "bridgerton.audius.co/searcher" "bridgerton.audius.co/trashid" "github.com/AudiusProject/audiusd/pkg/rewards" adapter "github.com/axiomhq/axiom-go/adapters/zap" "github.com/axiomhq/axiom-go/axiom" + "github.com/elastic/go-elasticsearch/v8" "github.com/ethereum/go-ethereum/crypto" "github.com/gagliardetto/solana-go/rpc" "github.com/gofiber/contrib/fiberzap/v2" @@ -130,6 +132,11 @@ func NewApiServer(config config.Config) *ApiServer { panic(err) } + esClient, err := searcher.Dial() + if err != nil { + panic(err) + } + app := &ApiServer{ App: fiber.New(fiber.Config{ JSONEncoder: json.Marshal, @@ -138,6 +145,7 @@ func NewApiServer(config config.Config) *ApiServer { }), pool: pool, queries: dbv1.New(pool), + esClient: esClient, logger: logger, started: time.Now(), resolveHandleCache: resolveHandleCache, @@ -265,6 +273,9 @@ func NewApiServer(config config.Config) *ApiServer { g.Get("/playlists/:playlistId/reposts", app.v1PlaylistReposts) g.Get("/playlists/:playlistId/favorites", app.v1PlaylistFavorites) + // Search + g.Get("/search/autocomplete", app.v1SearchAutocomplete) + // Developer Apps g.Get("/developer_apps/:address", app.v1DeveloperApps) @@ -305,6 +316,7 @@ type ApiServer struct { *fiber.App pool *pgxpool.Pool queries *dbv1.Queries + esClient *elasticsearch.Client logger *zap.Logger started time.Time resolveHandleCache otter.Cache[string, int32] diff --git a/api/v1_search_autocomplete.go b/api/v1_search_autocomplete.go new file mode 100644 index 00000000..173164ea --- /dev/null +++ b/api/v1_search_autocomplete.go @@ -0,0 +1,117 @@ +package api + +import ( + "fmt" + + "bridgerton.audius.co/api/dbv1" + "bridgerton.audius.co/searcher" + "github.com/gofiber/fiber/v2" + "golang.org/x/sync/errgroup" +) + +func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { + query := c.Query("query") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + + myId := app.getMyId(c) + + g := errgroup.Group{} + var users []dbv1.FullUser + var tracks []dbv1.FullTrack + var playlists []dbv1.FullPlaylist + + // users + g.Go(func() error { + + dsl := fmt.Sprintf(`{ + "query": { + "simple_query_string": { + "query": %q, + "default_operator": "AND" + } + } + }`, query+"*") + + userIds, err := searcher.SearchAndPluck(app.esClient, "users", dsl, limit, offset) + if err != nil { + return err + } + + users, err = app.queries.FullUsers(c.Context(), dbv1.GetUsersParams{ + Ids: userIds, + MyID: myId, + }) + return err + }) + + // tracks + g.Go(func() error { + dsl := fmt.Sprintf(`{ + "query": { + "simple_query_string": { + "query": %q, + "default_operator": "AND" + } + } + }`, query+"*") + + tracksIds, err := searcher.SearchAndPluck(app.esClient, "tracks", dsl, limit, offset) + if err != nil { + return err + } + + tracks, err = app.queries.FullTracks(c.Context(), dbv1.FullTracksParams{ + GetTracksParams: dbv1.GetTracksParams{ + Ids: tracksIds, + MyID: myId, + }, + }) + return err + }) + + // playlists + g.Go(func() error { + dsl := fmt.Sprintf(`{ + "query": { + "simple_query_string": { + "query": %q, + "default_operator": "AND" + } + } + }`, query+"*") + + playlistsIds, err := searcher.SearchAndPluck(app.esClient, "playlists", dsl, limit, offset) + if err != nil { + return err + } + + playlists, err = app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ + GetPlaylistsParams: dbv1.GetPlaylistsParams{ + Ids: playlistsIds, + MyID: myId, + }, + }) + return err + }) + + err := g.Wait() + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": fiber.Map{ + "users": users, + "tracks": tracks, + "playlists": playlists, + + // todos + "albums": []any{}, + "saved_albums": []any{}, + "saved_users": []any{}, + "saved_tracks": []any{}, + "saved_playlists": []any{}, + }, + }) +} diff --git a/searcher/conn.go b/searcher/conn.go new file mode 100644 index 00000000..25d30ca1 --- /dev/null +++ b/searcher/conn.go @@ -0,0 +1,13 @@ +package searcher + +import "github.com/elastic/go-elasticsearch/v8" + +func Dial() (*elasticsearch.Client, error) { + cfg := elasticsearch.Config{ + Addresses: []string{ + "http://35.238.44.255:21302", + }, + } + + return elasticsearch.NewClient(cfg) +} diff --git a/searcher/demo.go b/searcher/demo.go index 22766545..5374f994 100644 --- a/searcher/demo.go +++ b/searcher/demo.go @@ -23,17 +23,10 @@ func mustDialPostgres() *pgxpool.Pool { } func mustDialElasticsearch() *elasticsearch.Client { - cfg := elasticsearch.Config{ - Addresses: []string{ - "http://35.238.44.255:21302", - }, - } - - esc, err := elasticsearch.NewClient(cfg) + esc, err := Dial() if err != nil { log.Fatalf("Error creating the client: %s", err) } - return esc } diff --git a/searcher/search_and_pluck.go b/searcher/search_and_pluck.go new file mode 100644 index 00000000..1249bc77 --- /dev/null +++ b/searcher/search_and_pluck.go @@ -0,0 +1,42 @@ +package searcher + +import ( + "context" + "io" + "strings" + + "github.com/elastic/go-elasticsearch/v8" + "github.com/elastic/go-elasticsearch/v8/esapi" + "github.com/tidwall/gjson" +) + +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() + + body, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + + // fmt.Println("FOUND", index, string(body)) + + result := []int32{} + for _, hit := range gjson.GetBytes(body, "hits.hits").Array() { + id := hit.Get("_id").Int() + result = append(result, int32(id)) + } + + return result, nil +} From 8a17b7b03df78657eda4611a5dc10959c2980b79 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Wed, 21 May 2025 14:15:01 -0400 Subject: [PATCH 04/30] wip basic tests --- api/v1_search_autocomplete.go | 22 ++++++++++--- searcher/search_and_pluck.go | 7 ++++- searcher/track_dsl_test.go | 57 ++++++++++++++++++++++++++++++++++ searcher/user_dsl_test.go | 58 +++++++++++++++++++++++++++++++++++ 4 files changed, 139 insertions(+), 5 deletions(-) create mode 100644 searcher/track_dsl_test.go create mode 100644 searcher/user_dsl_test.go diff --git a/api/v1_search_autocomplete.go b/api/v1_search_autocomplete.go index 173164ea..0caccbe7 100644 --- a/api/v1_search_autocomplete.go +++ b/api/v1_search_autocomplete.go @@ -26,10 +26,24 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { dsl := fmt.Sprintf(`{ "query": { - "simple_query_string": { - "query": %q, - "default_operator": "AND" - } + "function_score": { + "simple_query_string": { + "query": %q, + "default_operator": "AND" + } + }, + "boost_mode": "sum", + "score_mode": "sum", + "functions": [ + { + "field_value_factor": { + "field": "follower_count", + "factor": 1, + "modifier": "log1p", + "missing": 0 + } + } + ] } }`, query+"*") diff --git a/searcher/search_and_pluck.go b/searcher/search_and_pluck.go index 1249bc77..94cea5a0 100644 --- a/searcher/search_and_pluck.go +++ b/searcher/search_and_pluck.go @@ -2,6 +2,7 @@ package searcher import ( "context" + "fmt" "io" "strings" @@ -25,12 +26,16 @@ func SearchAndPluck(esClient *elasticsearch.Client, index, dsl string, limit, of } 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 } - // fmt.Println("FOUND", index, string(body)) + fmt.Println("ES BODY", index, string(body)) result := []int32{} for _, hit := range gjson.GetBytes(body, "hits.hits").Array() { diff --git a/searcher/track_dsl_test.go b/searcher/track_dsl_test.go new file mode 100644 index 00000000..ac056e83 --- /dev/null +++ b/searcher/track_dsl_test.go @@ -0,0 +1,57 @@ +package searcher + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/elastic/go-elasticsearch/v8/esapi" + "github.com/stretchr/testify/require" + "github.com/tidwall/pretty" +) + +func TestTrackDsl(t *testing.T) { + esClient, err := Dial() + require.NoError(t, err) + + query := "fever" + + dsl := fmt.Sprintf(` + { + "query": { + "function_score": { + "query": { + "simple_query_string": { + "query": %q, + "default_operator": "AND" + } + }, + "boost_mode": "sum", + "score_mode": "sum", + "functions": [ + { + "field_value_factor": { + "field": "repost_count", + "factor": 1, + "modifier": "log1p", + "missing": 0 + } + } + ] + } + } + }`, query+"*") + + req := esapi.SearchRequest{ + Index: []string{"tracks"}, + Body: strings.NewReader(dsl), + } + + res, err := req.Do(context.Background(), esClient) + require.NoError(t, err) + + cool := pretty.Pretty([]byte(res.String())) + fmt.Println(string(cool)) + +} diff --git a/searcher/user_dsl_test.go b/searcher/user_dsl_test.go new file mode 100644 index 00000000..c095c858 --- /dev/null +++ b/searcher/user_dsl_test.go @@ -0,0 +1,58 @@ +package searcher + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/elastic/go-elasticsearch/v8/esapi" + "github.com/stretchr/testify/require" + "github.com/tidwall/pretty" +) + +func TestUserDsl(t *testing.T) { + query := "ray" + + esClient, err := Dial() + require.NoError(t, err) + + dsl := fmt.Sprintf(` + { + "query": { + "function_score": { + "query": { + "simple_query_string": { + "query": %q, + "default_operator": "AND" + } + }, + "boost_mode": "sum", + "score_mode": "sum", + "functions": [ + { + "field_value_factor": { + "field": "follower_count", + "factor": 1, + "modifier": "log1p", + "missing": 0 + } + } + ] + } + } + }`, query+"*") + + fmt.Println(dsl) + + req := esapi.SearchRequest{ + Index: []string{"tracks"}, + Body: strings.NewReader(dsl), + } + + res, err := req.Do(context.Background(), esClient) + require.NoError(t, err) + + cool := pretty.Pretty([]byte(res.String())) + fmt.Println(string(cool)) +} From 5f54627f0ea6b48c3ef152edb3697d4dceb2b531 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Wed, 21 May 2025 16:37:36 -0400 Subject: [PATCH 05/30] wip: add elastic dsl builder --- go.mod | 3 ++ go.sum | 9 +++++ searcher/track_dsl_test.go | 83 ++++++++++++++++++++++++++++++++++---- 3 files changed, 87 insertions(+), 8 deletions(-) diff --git a/go.mod b/go.mod index e31ed6e5..0396bf73 100644 --- a/go.mod +++ b/go.mod @@ -31,6 +31,7 @@ require ( github.com/DataDog/zstd v1.5.2 // indirect github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 // indirect github.com/andybalholm/brotli v1.1.1 // indirect + github.com/aquasecurity/esquery v0.2.0 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blendle/zapdriver v1.3.1 // indirect @@ -54,7 +55,9 @@ require ( github.com/dolthub/maphash v0.1.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/elastic/elastic-transport-go/v8 v8.7.0 // indirect + github.com/elastic/go-elasticsearch/v7 v7.17.10 // indirect github.com/fatih/color v1.18.0 // indirect + github.com/fatih/structs v1.1.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/gagliardetto/treeout v0.1.4 // indirect github.com/gammazero/deque v1.0.0 // indirect diff --git a/go.sum b/go.sum index 62c88238..6d46498c 100644 --- a/go.sum +++ b/go.sum @@ -12,6 +12,8 @@ github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 h1:MzBOUgng9or github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129/go.mod h1:rFgpPQZYZ8vdbc+48xibu8ALc3yeyd64IhHS+PU6Yyg= github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/aquasecurity/esquery v0.2.0 h1:9WWXve95TE8hbm3736WB7nS6Owl8UGDeu+0jiyE9ttA= +github.com/aquasecurity/esquery v0.2.0/go.mod h1:VU+CIFR6C+H142HHZf9RUkp4Eedpo9UrEKeCQHWf9ao= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/axiomhq/axiom-go v0.23.0 h1:kY+JkLubQ6ANwIp1O3J//YQe9OpdXFaW7xaj1wXvfps= @@ -75,6 +77,9 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/elastic/elastic-transport-go/v8 v8.7.0 h1:OgTneVuXP2uip4BA658Xi6Hfw+PeIOod2rY3GVMGoVE= github.com/elastic/elastic-transport-go/v8 v8.7.0/go.mod h1:YLHer5cj0csTzNFXoNQ8qhtGY1GTvSqPnKWKaqQE3Hk= +github.com/elastic/go-elasticsearch/v7 v7.6.0/go.mod h1:OJ4wdbtDNk5g503kvlHLyErCgQwwzmDtaFC4XyOxXA4= +github.com/elastic/go-elasticsearch/v7 v7.17.10 h1:TCQ8i4PmIJuBunvBS6bwT2ybzVFxxUhhltAs3Gyu1yo= +github.com/elastic/go-elasticsearch/v7 v7.17.10/go.mod h1:OJ4wdbtDNk5g503kvlHLyErCgQwwzmDtaFC4XyOxXA4= github.com/elastic/go-elasticsearch/v8 v8.18.0 h1:ANNq1h7DEiPUaALb8+5w3baQzaS08WfHV0DNzp0VG4M= github.com/elastic/go-elasticsearch/v8 v8.18.0/go.mod h1:WLqwXsJmQoYkoA9JBFeEwPkQhCfAZuUvfpdU/NvSSf0= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -85,6 +90,8 @@ github.com/ethereum/go-ethereum v1.15.8 h1:H6NilvRXFVoHiXZ3zkuTqKW5XcxjLZniV5Ujx github.com/ethereum/go-ethereum v1.15.8/go.mod h1:+S9k+jFzlyVTNcYGvqFhzN/SFhI6vA+aOY4T5tLSPL0= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= +github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= @@ -196,6 +203,8 @@ github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jgroeneveld/schema v1.0.0/go.mod h1:M14lv7sNMtGvo3ops1MwslaSYgDYxrSmbzWIQ0Mr5rs= +github.com/jgroeneveld/trial v2.0.0+incompatible/go.mod h1:I6INLW96EN8WysNBXUFI3M4RIC8ePg9ntAc/Wy+U/+M= github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= diff --git a/searcher/track_dsl_test.go b/searcher/track_dsl_test.go index ac056e83..7359bdbe 100644 --- a/searcher/track_dsl_test.go +++ b/searcher/track_dsl_test.go @@ -2,31 +2,88 @@ package searcher import ( "context" + "encoding/json" "fmt" "strings" "testing" + "github.com/aquasecurity/esquery" "github.com/elastic/go-elasticsearch/v8/esapi" "github.com/stretchr/testify/require" "github.com/tidwall/pretty" ) +type TrachSearchQuery struct { + Query string + MinBPM int + MaxBPM int + Genre string + MusicalKeys []string +} + +func (t *TrachSearchQuery) Map() map[string]any { + builder := esquery.Bool() + + if t.Query != "" { + builder.Must(esquery.Match("title", t.Query)) + } + + if t.MinBPM > 0 || t.MaxBPM > 0 { + bpmRange := esquery.Range("bpm") + if t.MinBPM > 0 { + bpmRange.Gte(t.MinBPM) + } + if t.MaxBPM > 0 { + bpmRange.Lte(t.MaxBPM) + } + builder.Filter(bpmRange) + } + + if t.Genre != "" { + builder.Filter(esquery.Match("genre", t.Genre)) + } + + if len(t.MusicalKeys) > 0 { + keys := []any{} + for _, k := range t.MusicalKeys { + keys = append(keys, k) + } + builder.Filter(esquery.Terms("musical_key.keyword", keys...)) + } + + return builder.Map() +} + +func (t *TrachSearchQuery) MustJSON() []byte { + innerDsl, err := json.Marshal(t.Map()) + if err != nil { + panic(err) + } + return innerDsl +} + func TestTrackDsl(t *testing.T) { esClient, err := Dial() require.NoError(t, err) - query := "fever" + ts := TrachSearchQuery{ + // Query: "fever", + MinBPM: 80, + MaxBPM: 220, + Genre: "Rap", + MusicalKeys: []string{"A minor", "B minor"}, + } + + { + j := ts.MustJSON() + fmt.Println(string(pretty.Pretty(j))) + } dsl := fmt.Sprintf(` { "query": { "function_score": { - "query": { - "simple_query_string": { - "query": %q, - "default_operator": "AND" - } - }, + "query": %s, "boost_mode": "sum", "score_mode": "sum", "functions": [ @@ -41,7 +98,9 @@ func TestTrackDsl(t *testing.T) { ] } } - }`, query+"*") + }`, ts.MustJSON()) + + fmt.Println(string(pretty.Pretty([]byte(dsl)))) req := esapi.SearchRequest{ Index: []string{"tracks"}, @@ -55,3 +114,11 @@ func TestTrackDsl(t *testing.T) { fmt.Println(string(cool)) } + +func pprint(m map[string]any) { + j, err := json.MarshalIndent(m, "", " ") + if err != nil { + panic(err) + } + fmt.Println(string(j)) +} From 028b3c65cfd5dba550b4e8c29b8bfba7bec748b1 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Thu, 22 May 2025 11:07:48 -0400 Subject: [PATCH 06/30] es dsl builders for users, tracks, playlists --- searcher/dsl_helpers.go | 51 +++++++++++++++++++++ searcher/dsl_test.go | 34 ++++++++++++++ searcher/playlist_dsl_test.go | 32 +++++++++++++ searcher/playlist_indexer.go | 1 + searcher/track_dsl_test.go | 84 +++++------------------------------ searcher/user_dsl_test.go | 65 ++++++++------------------- 6 files changed, 149 insertions(+), 118 deletions(-) create mode 100644 searcher/dsl_helpers.go create mode 100644 searcher/dsl_test.go create mode 100644 searcher/playlist_dsl_test.go diff --git a/searcher/dsl_helpers.go b/searcher/dsl_helpers.go new file mode 100644 index 00000000..94691eda --- /dev/null +++ b/searcher/dsl_helpers.go @@ -0,0 +1,51 @@ +package searcher + +import ( + "encoding/json" + "fmt" + + "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 functionScore(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": "sum", + "score_mode": "sum", + "functions": [ + { + "field_value_factor": { + "field": %q, + "factor": 1, + "modifier": "log1p", + "missing": 0 + } + } + ] + } + } + }`, innerJson, scoreField) + + pprintJson(dsl) + return dsl +} + +func pprintJson(j string) { + fmt.Println(string(pretty.Pretty([]byte(j)))) +} diff --git a/searcher/dsl_test.go b/searcher/dsl_test.go new file mode 100644 index 00000000..eb238e28 --- /dev/null +++ b/searcher/dsl_test.go @@ -0,0 +1,34 @@ +package searcher + +import ( + "context" + "strings" + "testing" + + "github.com/elastic/go-elasticsearch/v8/esapi" + "github.com/stretchr/testify/require" +) + +func testSearch(t *testing.T, indexName, dsl string) { + t.Helper() + + pprintJson(dsl) + + esClient, err := Dial() + require.NoError(t, err) + + req := esapi.SearchRequest{ + Index: []string{indexName}, + Body: strings.NewReader(dsl), + } + + res, err := req.Do(context.Background(), esClient) + require.NoError(t, err) + body := res.String() + + if res.IsError() { + require.FailNow(t, body) + } + + pprintJson(body) +} diff --git a/searcher/playlist_dsl_test.go b/searcher/playlist_dsl_test.go new file mode 100644 index 00000000..db1f82ca --- /dev/null +++ b/searcher/playlist_dsl_test.go @@ -0,0 +1,32 @@ +package searcher + +import ( + "testing" + + "github.com/aquasecurity/esquery" +) + +type PlaylistSearchQuery struct { + Query string + Genres []string + Moods []string +} + +func (q *PlaylistSearchQuery) Map() map[string]any { + builder := esquery.Bool() + + if q.Query != "" { + builder.Must(esquery.Match("title", q.Query)) + } + + return builder.Map() +} + +func TestPlaylistDsl(t *testing.T) { + q := &PlaylistSearchQuery{ + Query: "rap", + } + + dsl := functionScore("repost_count", q.Map()) + testSearch(t, "playlists", dsl) +} diff --git a/searcher/playlist_indexer.go b/searcher/playlist_indexer.go index 71d89eed..6274499e 100644 --- a/searcher/playlist_indexer.go +++ b/searcher/playlist_indexer.go @@ -23,6 +23,7 @@ func (pi *PlaylistIndexer) createIndex(drop bool) error { } func (pi *PlaylistIndexer) indexAll() error { + // todo: track stubs sql := ` SELECT playlist_id, diff --git a/searcher/track_dsl_test.go b/searcher/track_dsl_test.go index 7359bdbe..3b8518fb 100644 --- a/searcher/track_dsl_test.go +++ b/searcher/track_dsl_test.go @@ -1,23 +1,17 @@ package searcher import ( - "context" - "encoding/json" - "fmt" - "strings" "testing" "github.com/aquasecurity/esquery" - "github.com/elastic/go-elasticsearch/v8/esapi" - "github.com/stretchr/testify/require" - "github.com/tidwall/pretty" ) type TrachSearchQuery struct { Query string MinBPM int MaxBPM int - Genre string + Genres []string + Moods []string MusicalKeys []string } @@ -39,86 +33,32 @@ func (t *TrachSearchQuery) Map() map[string]any { builder.Filter(bpmRange) } - if t.Genre != "" { - builder.Filter(esquery.Match("genre", t.Genre)) + if len(t.Genres) > 0 { + builder.Filter(esquery.Match("genre", toAnySlice(t.Genres)...)) + } + + if len(t.Moods) > 0 { + builder.Filter(esquery.Match("mood", toAnySlice(t.Moods)...)) } if len(t.MusicalKeys) > 0 { - keys := []any{} - for _, k := range t.MusicalKeys { - keys = append(keys, k) - } - builder.Filter(esquery.Terms("musical_key.keyword", keys...)) + builder.Filter(esquery.Terms("musical_key.keyword", toAnySlice(t.MusicalKeys)...)) } return builder.Map() } -func (t *TrachSearchQuery) MustJSON() []byte { - innerDsl, err := json.Marshal(t.Map()) - if err != nil { - panic(err) - } - return innerDsl -} - func TestTrackDsl(t *testing.T) { - esClient, err := Dial() - require.NoError(t, err) ts := TrachSearchQuery{ // Query: "fever", MinBPM: 80, MaxBPM: 220, - Genre: "Rap", + Genres: []string{"Rap"}, MusicalKeys: []string{"A minor", "B minor"}, } - { - j := ts.MustJSON() - fmt.Println(string(pretty.Pretty(j))) - } - - dsl := fmt.Sprintf(` - { - "query": { - "function_score": { - "query": %s, - "boost_mode": "sum", - "score_mode": "sum", - "functions": [ - { - "field_value_factor": { - "field": "repost_count", - "factor": 1, - "modifier": "log1p", - "missing": 0 - } - } - ] - } - } - }`, ts.MustJSON()) + dsl := functionScore("repost_count", ts.Map()) + testSearch(t, "playlists", dsl) - fmt.Println(string(pretty.Pretty([]byte(dsl)))) - - req := esapi.SearchRequest{ - Index: []string{"tracks"}, - Body: strings.NewReader(dsl), - } - - res, err := req.Do(context.Background(), esClient) - require.NoError(t, err) - - cool := pretty.Pretty([]byte(res.String())) - fmt.Println(string(cool)) - -} - -func pprint(m map[string]any) { - j, err := json.MarshalIndent(m, "", " ") - if err != nil { - panic(err) - } - fmt.Println(string(j)) } diff --git a/searcher/user_dsl_test.go b/searcher/user_dsl_test.go index c095c858..44684f3a 100644 --- a/searcher/user_dsl_test.go +++ b/searcher/user_dsl_test.go @@ -1,58 +1,31 @@ package searcher import ( - "context" - "fmt" - "strings" "testing" - "github.com/elastic/go-elasticsearch/v8/esapi" - "github.com/stretchr/testify/require" - "github.com/tidwall/pretty" + "github.com/aquasecurity/esquery" ) +type UserSearchQuery struct { + Query string `json:"query"` +} + +func (q *UserSearchQuery) Map() map[string]any { + builder := esquery.Bool() + + if q.Query != "" { + builder.Must(esquery.MultiMatch(q.Query).Fields("name", "handle")) + } + + return builder.Map() +} + func TestUserDsl(t *testing.T) { - query := "ray" - - esClient, err := Dial() - require.NoError(t, err) - - dsl := fmt.Sprintf(` - { - "query": { - "function_score": { - "query": { - "simple_query_string": { - "query": %q, - "default_operator": "AND" - } - }, - "boost_mode": "sum", - "score_mode": "sum", - "functions": [ - { - "field_value_factor": { - "field": "follower_count", - "factor": 1, - "modifier": "log1p", - "missing": 0 - } - } - ] - } - } - }`, query+"*") - - fmt.Println(dsl) - - req := esapi.SearchRequest{ - Index: []string{"tracks"}, - Body: strings.NewReader(dsl), + q := &UserSearchQuery{ + Query: "ray", } - res, err := req.Do(context.Background(), esClient) - require.NoError(t, err) + dsl := functionScore("followers_count", q.Map()) - cool := pretty.Pretty([]byte(res.String())) - fmt.Println(string(cool)) + testSearch(t, "users", dsl) } From a7275fdb41f1033fa433f9a2158350fae17c6bab Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Thu, 22 May 2025 15:39:13 -0400 Subject: [PATCH 07/30] Use dsl builders, add searchtest.html Query still needs some work to match current results. --- api/v1_search_autocomplete.go | 81 ++++++------ searcher/dsl_helpers.go | 2 +- searcher/dsl_test.go | 1 + ...laylist_dsl_test.go => playlist_search.go} | 20 +-- searcher/playlist_search_test.go | 14 ++ .../{track_dsl_test.go => track_search.go} | 21 +-- searcher/track_search_test.go | 20 +++ searcher/{user_dsl_test.go => user_search.go} | 16 +-- searcher/user_search_test.go | 15 +++ static/searchtest.html | 125 ++++++++++++++++++ 10 files changed, 224 insertions(+), 91 deletions(-) rename searcher/{playlist_dsl_test.go => playlist_search.go} (55%) create mode 100644 searcher/playlist_search_test.go rename searcher/{track_dsl_test.go => track_search.go} (68%) create mode 100644 searcher/track_search_test.go rename searcher/{user_dsl_test.go => user_search.go} (55%) create mode 100644 searcher/user_search_test.go create mode 100644 static/searchtest.html diff --git a/api/v1_search_autocomplete.go b/api/v1_search_autocomplete.go index 0caccbe7..a8c60e56 100644 --- a/api/v1_search_autocomplete.go +++ b/api/v1_search_autocomplete.go @@ -1,8 +1,6 @@ package api import ( - "fmt" - "bridgerton.audius.co/api/dbv1" "bridgerton.audius.co/searcher" "github.com/gofiber/fiber/v2" @@ -20,33 +18,15 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { var users []dbv1.FullUser var tracks []dbv1.FullTrack var playlists []dbv1.FullPlaylist + var albums []dbv1.FullPlaylist // users g.Go(func() error { + q := searcher.UserSearchQuery{ + Query: query, + } - dsl := fmt.Sprintf(`{ - "query": { - "function_score": { - "simple_query_string": { - "query": %q, - "default_operator": "AND" - } - }, - "boost_mode": "sum", - "score_mode": "sum", - "functions": [ - { - "field_value_factor": { - "field": "follower_count", - "factor": 1, - "modifier": "log1p", - "missing": 0 - } - } - ] - } - }`, query+"*") - + dsl := searcher.BuildFunctionScoreDSL("follower_count", q.Map()) userIds, err := searcher.SearchAndPluck(app.esClient, "users", dsl, limit, offset) if err != nil { return err @@ -61,14 +41,11 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { // tracks g.Go(func() error { - dsl := fmt.Sprintf(`{ - "query": { - "simple_query_string": { - "query": %q, - "default_operator": "AND" - } - } - }`, query+"*") + q := searcher.TrackSearchQuery{ + Query: query, + } + + dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) tracksIds, err := searcher.SearchAndPluck(app.esClient, "tracks", dsl, limit, offset) if err != nil { @@ -86,14 +63,11 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { // playlists g.Go(func() error { - dsl := fmt.Sprintf(`{ - "query": { - "simple_query_string": { - "query": %q, - "default_operator": "AND" - } - } - }`, query+"*") + q := searcher.PlaylistSearchQuery{ + Query: query, + } + + dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) playlistsIds, err := searcher.SearchAndPluck(app.esClient, "playlists", dsl, limit, offset) if err != nil { @@ -109,6 +83,29 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { return err }) + // albums + g.Go(func() error { + q := searcher.PlaylistSearchQuery{ + Query: query, + IsAlbum: true, + } + + dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) + + playlistsIds, err := searcher.SearchAndPluck(app.esClient, "playlists", dsl, limit, offset) + if err != nil { + return err + } + + albums, err = app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ + GetPlaylistsParams: dbv1.GetPlaylistsParams{ + Ids: playlistsIds, + MyID: myId, + }, + }) + return err + }) + err := g.Wait() if err != nil { return err @@ -119,9 +116,9 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { "users": users, "tracks": tracks, "playlists": playlists, + "albums": albums, // todos - "albums": []any{}, "saved_albums": []any{}, "saved_users": []any{}, "saved_tracks": []any{}, diff --git a/searcher/dsl_helpers.go b/searcher/dsl_helpers.go index 94691eda..bb5c62af 100644 --- a/searcher/dsl_helpers.go +++ b/searcher/dsl_helpers.go @@ -15,7 +15,7 @@ func toAnySlice[T any](slice []T) []any { return result } -func functionScore(scoreField string, innerQuery map[string]any) string { +func BuildFunctionScoreDSL(scoreField string, innerQuery map[string]any) string { innerJson, err := json.Marshal(innerQuery) if err != nil { panic(err) diff --git a/searcher/dsl_test.go b/searcher/dsl_test.go index eb238e28..5bf3fe25 100644 --- a/searcher/dsl_test.go +++ b/searcher/dsl_test.go @@ -31,4 +31,5 @@ func testSearch(t *testing.T, indexName, dsl string) { } pprintJson(body) + // todo: assert not empty and stuff... } diff --git a/searcher/playlist_dsl_test.go b/searcher/playlist_search.go similarity index 55% rename from searcher/playlist_dsl_test.go rename to searcher/playlist_search.go index db1f82ca..142e2ac5 100644 --- a/searcher/playlist_dsl_test.go +++ b/searcher/playlist_search.go @@ -1,15 +1,14 @@ package searcher import ( - "testing" - "github.com/aquasecurity/esquery" ) type PlaylistSearchQuery struct { - Query string - Genres []string - Moods []string + Query string + Genres []string + Moods []string + IsAlbum bool } func (q *PlaylistSearchQuery) Map() map[string]any { @@ -19,14 +18,7 @@ func (q *PlaylistSearchQuery) Map() map[string]any { builder.Must(esquery.Match("title", q.Query)) } - return builder.Map() -} - -func TestPlaylistDsl(t *testing.T) { - q := &PlaylistSearchQuery{ - Query: "rap", - } + builder.Filter(esquery.Term("is_album", q.IsAlbum)) - dsl := functionScore("repost_count", q.Map()) - testSearch(t, "playlists", dsl) + return builder.Map() } diff --git a/searcher/playlist_search_test.go b/searcher/playlist_search_test.go new file mode 100644 index 00000000..6e2994ba --- /dev/null +++ b/searcher/playlist_search_test.go @@ -0,0 +1,14 @@ +package searcher + +import ( + "testing" +) + +func TestPlaylistDsl(t *testing.T) { + q := &PlaylistSearchQuery{ + Query: "rap", + } + + dsl := BuildFunctionScoreDSL("repost_count", q.Map()) + testSearch(t, "playlists", dsl) +} diff --git a/searcher/track_dsl_test.go b/searcher/track_search.go similarity index 68% rename from searcher/track_dsl_test.go rename to searcher/track_search.go index 3b8518fb..51d54345 100644 --- a/searcher/track_dsl_test.go +++ b/searcher/track_search.go @@ -1,12 +1,10 @@ package searcher import ( - "testing" - "github.com/aquasecurity/esquery" ) -type TrachSearchQuery struct { +type TrackSearchQuery struct { Query string MinBPM int MaxBPM int @@ -15,7 +13,7 @@ type TrachSearchQuery struct { MusicalKeys []string } -func (t *TrachSearchQuery) Map() map[string]any { +func (t *TrackSearchQuery) Map() map[string]any { builder := esquery.Bool() if t.Query != "" { @@ -47,18 +45,3 @@ func (t *TrachSearchQuery) Map() map[string]any { return builder.Map() } - -func TestTrackDsl(t *testing.T) { - - ts := TrachSearchQuery{ - // Query: "fever", - MinBPM: 80, - MaxBPM: 220, - Genres: []string{"Rap"}, - MusicalKeys: []string{"A minor", "B minor"}, - } - - dsl := functionScore("repost_count", ts.Map()) - testSearch(t, "playlists", dsl) - -} diff --git a/searcher/track_search_test.go b/searcher/track_search_test.go new file mode 100644 index 00000000..4ede654c --- /dev/null +++ b/searcher/track_search_test.go @@ -0,0 +1,20 @@ +package searcher + +import ( + "testing" +) + +func TestTrackDsl(t *testing.T) { + + ts := TrackSearchQuery{ + // Query: "fever", + MinBPM: 80, + MaxBPM: 220, + Genres: []string{"Rap"}, + MusicalKeys: []string{"A minor", "B minor"}, + } + + dsl := BuildFunctionScoreDSL("repost_count", ts.Map()) + testSearch(t, "playlists", dsl) + +} diff --git a/searcher/user_dsl_test.go b/searcher/user_search.go similarity index 55% rename from searcher/user_dsl_test.go rename to searcher/user_search.go index 44684f3a..2076383b 100644 --- a/searcher/user_dsl_test.go +++ b/searcher/user_search.go @@ -1,10 +1,6 @@ package searcher -import ( - "testing" - - "github.com/aquasecurity/esquery" -) +import "github.com/aquasecurity/esquery" type UserSearchQuery struct { Query string `json:"query"` @@ -19,13 +15,3 @@ func (q *UserSearchQuery) Map() map[string]any { return builder.Map() } - -func TestUserDsl(t *testing.T) { - q := &UserSearchQuery{ - Query: "ray", - } - - dsl := functionScore("followers_count", q.Map()) - - testSearch(t, "users", dsl) -} diff --git a/searcher/user_search_test.go b/searcher/user_search_test.go new file mode 100644 index 00000000..0ac8257d --- /dev/null +++ b/searcher/user_search_test.go @@ -0,0 +1,15 @@ +package searcher + +import ( + "testing" +) + +func TestUserDsl(t *testing.T) { + q := &UserSearchQuery{ + Query: "ray", + } + + dsl := BuildFunctionScoreDSL("followers_count", q.Map()) + + testSearch(t, "users", dsl) +} diff --git a/static/searchtest.html b/static/searchtest.html new file mode 100644 index 00000000..86a32007 --- /dev/null +++ b/static/searchtest.html @@ -0,0 +1,125 @@ + + + + + Search Test + + + +
+ + +
+ +
+
+
+
+
+
+ + + + From 051156a3bb90d569427034be0ba602dd864237fd Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Wed, 28 May 2025 15:40:28 -0400 Subject: [PATCH 08/30] socials index to boost items you have interacted with. --- go.mod | 6 ++- go.sum | 3 ++ searcher/demo.go | 16 +++++- searcher/dsl_helpers.go | 15 ++++++ searcher/dsl_test.go | 44 ++++++++++++++++ searcher/playlist_search.go | 16 ++++++ searcher/playlist_search_test.go | 3 +- searcher/social_indexer.go | 90 ++++++++++++++++++++++++++++++++ searcher/track_indexer.go | 3 +- searcher/track_search.go | 17 ++++++ searcher/track_search_test.go | 5 +- searcher/user_indexer.go | 24 +-------- searcher/user_search.go | 20 ++++++- searcher/user_search_test.go | 1 + utils/json_assert.go | 29 ++++++++++ 15 files changed, 261 insertions(+), 31 deletions(-) create mode 100644 searcher/social_indexer.go create mode 100644 utils/json_assert.go diff --git a/go.mod b/go.mod index 0396bf73..faeb425f 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.24.1 require ( github.com/AudiusProject/audiusd v0.0.0-20250423205417-9adf00a64112 + github.com/aquasecurity/esquery v0.2.0 github.com/axiomhq/axiom-go v0.23.0 github.com/elastic/go-elasticsearch/v8 v8.18.0 github.com/ethereum/go-ethereum v1.15.8 @@ -19,7 +20,10 @@ require ( github.com/segmentio/encoding v0.4.1 github.com/speps/go-hashids/v2 v2.0.1 github.com/stretchr/testify v1.10.0 + github.com/test-go/testify v1.1.4 github.com/tidwall/gjson v1.18.0 + github.com/tidwall/pretty v1.2.1 + github.com/tidwall/sjson v1.2.5 github.com/valyala/fasthttp v1.59.0 go.uber.org/zap v1.27.0 golang.org/x/sync v0.13.0 @@ -31,7 +35,6 @@ require ( github.com/DataDog/zstd v1.5.2 // indirect github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 // indirect github.com/andybalholm/brotli v1.1.1 // indirect - github.com/aquasecurity/esquery v0.2.0 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blendle/zapdriver v1.3.1 // indirect @@ -126,7 +129,6 @@ require ( github.com/supranational/blst v0.3.14 // indirect github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect github.com/tidwall/match v1.1.1 // indirect - github.com/tidwall/pretty v1.2.1 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 // indirect go.mongodb.org/mongo-driver v1.14.0 // indirect diff --git a/go.sum b/go.sum index 6d46498c..eb11eff3 100644 --- a/go.sum +++ b/go.sum @@ -203,7 +203,9 @@ github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jgroeneveld/schema v1.0.0 h1:J0E10CrOkiSEsw6dfb1IfrDJD14pf6QLVJ3tRPl/syI= github.com/jgroeneveld/schema v1.0.0/go.mod h1:M14lv7sNMtGvo3ops1MwslaSYgDYxrSmbzWIQ0Mr5rs= +github.com/jgroeneveld/trial v2.0.0+incompatible h1:d59ctdgor+VqdZCAiUfVN8K13s0ALDioG5DWwZNtRuQ= github.com/jgroeneveld/trial v2.0.0+incompatible/go.mod h1:I6INLW96EN8WysNBXUFI3M4RIC8ePg9ntAc/Wy+U/+M= github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= @@ -325,6 +327,7 @@ github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70 github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= github.com/test-go/testify v1.1.4 h1:Tf9lntrKUMHiXQ07qBScBTSA0dhYQlu83hswqelv1iE= github.com/test-go/testify v1.1.4/go.mod h1:rH7cfJo/47vWGdi4GPj16x3/t1xGOj2YxzmNQzk2ghU= +github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= diff --git a/searcher/demo.go b/searcher/demo.go index 5374f994..8ad46602 100644 --- a/searcher/demo.go +++ b/searcher/demo.go @@ -69,6 +69,17 @@ func trackDemo(base *BaseIndexer) { i.search("rap") } +func socialDemo(base *BaseIndexer) { + i := &SocialIndexer{base} + + if err := i.createIndex(true); err != nil { + panic(err) + } + if err := i.indexAll(); err != nil { + panic(err) + } +} + func Demo() { pool := mustDialPostgres() esc := mustDialElasticsearch() @@ -78,6 +89,9 @@ func Demo() { esc, } - // playlistDemo(baseIndexer) + playlistDemo(baseIndexer) trackDemo(baseIndexer) + userDemo(baseIndexer) + socialDemo(baseIndexer) + } diff --git a/searcher/dsl_helpers.go b/searcher/dsl_helpers.go index bb5c62af..e7a1c432 100644 --- a/searcher/dsl_helpers.go +++ b/searcher/dsl_helpers.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/tidwall/pretty" + "github.com/tidwall/sjson" ) func toAnySlice[T any](slice []T) []any { @@ -49,3 +50,17 @@ func BuildFunctionScoreDSL(scoreField string, innerQuery map[string]any) string func pprintJson(j string) { fmt.Println(string(pretty.Pretty([]byte(j)))) } + +func commonIndexSettings(mapping string) string { + mustSet := func(key string, value any) { + var err error + mapping, err = sjson.Set(mapping, key, value) + if err != nil { + panic(err) + } + } + + mustSet("settings.number_of_shards", 1) + mustSet("settings.number_of_replicas", 0) + return mapping +} diff --git a/searcher/dsl_test.go b/searcher/dsl_test.go index 5bf3fe25..3e8f3cda 100644 --- a/searcher/dsl_test.go +++ b/searcher/dsl_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "bridgerton.audius.co/utils" "github.com/elastic/go-elasticsearch/v8/esapi" "github.com/stretchr/testify/require" ) @@ -33,3 +34,46 @@ func testSearch(t *testing.T, indexName, dsl string) { pprintJson(body) // todo: assert not empty and stuff... } + +func TestCommonIndexSettings(t *testing.T) { + { + mapping := `{ + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "handle": { + "type": "text" + }, + "location": { + "type": "text" + }, + "follower_count": { + "type": "integer" + }, + "track_count": { + "type": "integer" + } + } + } + }` + + m2 := commonIndexSettings(mapping) + + utils.JsonAssert(t, []byte(m2), map[string]any{ + "mappings.properties.name.type": "text", + "settings.number_of_shards": 1, + "settings.number_of_replicas": 0, + }) + } + + // works with empty mapping + { + m2 := commonIndexSettings(``) + utils.JsonAssert(t, []byte(m2), map[string]any{ + "settings.number_of_shards": 1, + "settings.number_of_replicas": 0, + }) + } +} diff --git a/searcher/playlist_search.go b/searcher/playlist_search.go index 142e2ac5..98c3dd51 100644 --- a/searcher/playlist_search.go +++ b/searcher/playlist_search.go @@ -1,6 +1,8 @@ package searcher import ( + "fmt" + "github.com/aquasecurity/esquery" ) @@ -9,6 +11,7 @@ type PlaylistSearchQuery struct { Genres []string Moods []string IsAlbum bool + MyID int } func (q *PlaylistSearchQuery) Map() map[string]any { @@ -20,5 +23,18 @@ func (q *PlaylistSearchQuery) Map() map[string]any { builder.Filter(esquery.Term("is_album", q.IsAlbum)) + 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() } diff --git a/searcher/playlist_search_test.go b/searcher/playlist_search_test.go index 6e2994ba..23725d20 100644 --- a/searcher/playlist_search_test.go +++ b/searcher/playlist_search_test.go @@ -6,7 +6,8 @@ import ( func TestPlaylistDsl(t *testing.T) { q := &PlaylistSearchQuery{ - Query: "rap", + Query: "hot", + MyID: 1, } dsl := BuildFunctionScoreDSL("repost_count", q.Map()) diff --git a/searcher/social_indexer.go b/searcher/social_indexer.go new file mode 100644 index 00000000..13a21cf3 --- /dev/null +++ b/searcher/social_indexer.go @@ -0,0 +1,90 @@ +package searcher + +// user id => list of following, repost (tracks), save (tracks), repost (playlists), repost (playlist) +type SocialIndexer struct { + *BaseIndexer +} + +func (ui *SocialIndexer) createIndex(drop bool) error { + mapping := `{ + "mappings": { + "properties": { + "saved_track_ids": { "type": "keyword" }, + "reposted_track_ids": { "type": "keyword" }, + "saved_playlist_ids": { "type": "keyword" }, + "reposted_playlist_ids": { "type": "keyword" }, + "following_user_ids": { "type": "keyword" } + } + } + }` + return ui.BaseIndexer.createIndex("socials", mapping, drop) +} + +func (ui *SocialIndexer) indexAll() error { + sql := ` + select + user_id, + json_build_object ( + 'saved_track_ids', + ( + select + array_agg (save_item_id) + from + saves + where + save_type = 'track' + and is_delete = false + and user_id = users.user_id + ), + 'reposted_track_ids', + ( + select + array_agg (repost_item_id) + from + reposts + where + repost_type = 'track' + and is_delete = false + and user_id = users.user_id + ), + 'saved_playlist_ids', + ( + select + array_agg (save_item_id) + from + saves + where + save_type != 'track' + and is_delete = false + and user_id = users.user_id + ), + 'reposted_playlist_ids', + ( + select + array_agg (repost_item_id) + from + reposts + where + repost_type != 'track' + and is_delete = false + and user_id = users.user_id + ), + 'following_user_ids', + ( + select + array_agg (followee_user_id) + from + follows + where + is_delete = false + and follower_user_id = users.user_id + ) + ) as doc + from + users + where + user_id < 1000 + ` + + return ui.bulkIndexQuery("socials", sql) +} diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go index cf511311..8dd4bcd1 100644 --- a/searcher/track_indexer.go +++ b/searcher/track_indexer.go @@ -49,7 +49,8 @@ func (ti *TrackIndexer) indexAll() error { JOIN aggregate_track USING (track_id) JOIN users ON owner_id = user_id JOIN aggregate_user USING (user_id) - LIMIT 10000` + WHERE track_id < 100000 + LIMIT 100000` return ti.bulkIndexQuery("tracks", sql) } diff --git a/searcher/track_search.go b/searcher/track_search.go index 51d54345..e24f6479 100644 --- a/searcher/track_search.go +++ b/searcher/track_search.go @@ -1,6 +1,8 @@ package searcher import ( + "fmt" + "github.com/aquasecurity/esquery" ) @@ -11,6 +13,7 @@ type TrackSearchQuery struct { Genres []string Moods []string MusicalKeys []string + MyID int } func (t *TrackSearchQuery) Map() map[string]any { @@ -43,5 +46,19 @@ func (t *TrackSearchQuery) Map() map[string]any { builder.Filter(esquery.Terms("musical_key.keyword", toAnySlice(t.MusicalKeys)...)) } + // boost tracks that are saved / reposted + if t.MyID > 0 { + builder.Should(esquery.CustomQuery(map[string]any{ + "terms": map[string]any{ + "_id": map[string]any{ + "index": "socials", + "id": fmt.Sprintf("%d", t.MyID), + "path": "reposted_track_ids", + }, + "boost": 10, + }, + })) + } + return builder.Map() } diff --git a/searcher/track_search_test.go b/searcher/track_search_test.go index 4ede654c..6c12ed70 100644 --- a/searcher/track_search_test.go +++ b/searcher/track_search_test.go @@ -7,14 +7,15 @@ import ( func TestTrackDsl(t *testing.T) { ts := TrackSearchQuery{ - // Query: "fever", + Query: "KING", MinBPM: 80, MaxBPM: 220, Genres: []string{"Rap"}, MusicalKeys: []string{"A minor", "B minor"}, + MyID: 1, } dsl := BuildFunctionScoreDSL("repost_count", ts.Map()) - testSearch(t, "playlists", dsl) + testSearch(t, "tracks", dsl) } diff --git a/searcher/user_indexer.go b/searcher/user_indexer.go index 3e2fbde9..2a227925 100644 --- a/searcher/user_indexer.go +++ b/searcher/user_indexer.go @@ -25,29 +25,7 @@ type UserIndexer struct { } func (ui *UserIndexer) createIndex(drop bool) error { - - mapping := `{ - "mappings": { - "properties": { - "name": { - "type": "text" - }, - "handle": { - "type": "text" - }, - "location": { - "type": "text" - }, - "follower_count": { - "type": "integer" - }, - "track_count": { - "type": "integer" - } - } - } - }` - + mapping := `` return ui.BaseIndexer.createIndex("users", mapping, drop) } diff --git a/searcher/user_search.go b/searcher/user_search.go index 2076383b..c7fbd810 100644 --- a/searcher/user_search.go +++ b/searcher/user_search.go @@ -1,9 +1,14 @@ package searcher -import "github.com/aquasecurity/esquery" +import ( + "fmt" + + "github.com/aquasecurity/esquery" +) type UserSearchQuery struct { Query string `json:"query"` + MyID int `json:"my_id"` } func (q *UserSearchQuery) Map() map[string]any { @@ -13,5 +18,18 @@ func (q *UserSearchQuery) Map() map[string]any { builder.Must(esquery.MultiMatch(q.Query).Fields("name", "handle")) } + 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": "following_user_ids", + }, + "boost": 10, + }, + })) + } + return builder.Map() } diff --git a/searcher/user_search_test.go b/searcher/user_search_test.go index 0ac8257d..4ee0e84e 100644 --- a/searcher/user_search_test.go +++ b/searcher/user_search_test.go @@ -7,6 +7,7 @@ import ( func TestUserDsl(t *testing.T) { q := &UserSearchQuery{ Query: "ray", + MyID: 1, } dsl := BuildFunctionScoreDSL("followers_count", q.Map()) diff --git a/utils/json_assert.go b/utils/json_assert.go new file mode 100644 index 00000000..92857d6b --- /dev/null +++ b/utils/json_assert.go @@ -0,0 +1,29 @@ +package utils + +import ( + "fmt" + "testing" + + "github.com/test-go/testify/require" + "github.com/tidwall/gjson" +) + +func JsonAssert(t *testing.T, body []byte, expectations map[string]any) { + for path, expectation := range expectations { + var actual any + switch v := expectation.(type) { + case string: + actual = gjson.GetBytes(body, path).String() + case bool: + actual = gjson.GetBytes(body, path).Bool() + case float64: + actual = gjson.GetBytes(body, path).Float() + case int: + actual = int(gjson.GetBytes(body, path).Int()) + default: + t.Errorf("unsupported type for expectation: %T", v) + } + msg := fmt.Sprintf("Expected %s to be %v got %v", path, expectation, actual) + require.Equal(t, expectation, actual, msg) + } +} From e73d1fa8d298f49446bf6accf1db02880608e970 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Thu, 29 May 2025 13:33:05 -0400 Subject: [PATCH 09/30] improve reindex cli. Do all the data. --- main.go | 7 ++-- searcher/base_indexer.go | 4 ++- searcher/playlist_indexer.go | 53 +----------------------------- searcher/{demo.go => reindex.go} | 35 +++++++++++--------- searcher/social_indexer.go | 5 ++- searcher/track_indexer.go | 55 +------------------------------- searcher/user_indexer.go | 49 +--------------------------- searcher/user_search.go | 2 +- 8 files changed, 33 insertions(+), 177 deletions(-) rename searcher/{demo.go => reindex.go} (67%) diff --git a/main.go b/main.go index f9c2e584..24a4d76e 100644 --- a/main.go +++ b/main.go @@ -11,9 +11,10 @@ import ( func main() { - if len(os.Args) > 1 && os.Args[1] == "search" { - fmt.Println("search time...") - searcher.Demo() + if len(os.Args) > 1 && os.Args[1] == "reindex" { + collections := os.Args[2:] + fmt.Println("reindex", collections) + searcher.Reindex(collections...) return } diff --git a/searcher/base_indexer.go b/searcher/base_indexer.go index 74c8f6a8..dbb48411 100644 --- a/searcher/base_indexer.go +++ b/searcher/base_indexer.go @@ -70,7 +70,7 @@ func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { DocumentID: fmt.Sprintf("%d", id), Body: strings.NewReader(doc), OnSuccess: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem) { - fmt.Println("index", id, doc) + // fmt.Println("index", index, id) }, OnFailure: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem, err error) { if err != nil { @@ -95,5 +95,7 @@ func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { log.Fatalf("Unexpected error: %s", err) } + fmt.Printf("stats: %s %+v \n", index, bulk.Stats()) + return nil } diff --git a/searcher/playlist_indexer.go b/searcher/playlist_indexer.go index 6274499e..d35c25af 100644 --- a/searcher/playlist_indexer.go +++ b/searcher/playlist_indexer.go @@ -1,11 +1,5 @@ package searcher -import ( - "encoding/json" - "fmt" - "strings" -) - type PlaylistIndexer struct { *BaseIndexer } @@ -48,52 +42,7 @@ func (pi *PlaylistIndexer) indexAll() error { JOIN aggregate_playlist USING (playlist_id) JOIN users ON playlist_owner_id = user_id JOIN aggregate_user USING (user_id) - LIMIT 10000` + ` return pi.bulkIndexQuery("playlists", sql) } - -func (pi *PlaylistIndexer) search(q string) { - query := fmt.Sprintf(`{ - "query": { - "multi_match": { - "query": %q, - "fields": ["title", "description"] - } - } - }`, q) - - fmt.Println(query) - - res, err := pi.esc.Search( - pi.esc.Search.WithIndex("playlists"), - pi.esc.Search.WithBody(strings.NewReader(query)), - ) - if err != nil { - fmt.Println("es search error:", err) - return - } - defer res.Body.Close() - - type hit struct { - ID string `json:"_id"` - } - type hits struct { - Hits struct { - Hits []hit `json:"hits"` - } `json:"hits"` - } - - var result hits - if err := json.NewDecoder(res.Body).Decode(&result); err != nil { - fmt.Println("decode error:", err) - return - } - - var ids []string - for _, h := range result.Hits.Hits { - ids = append(ids, h.ID) - } - - fmt.Println("found ids:", ids) -} diff --git a/searcher/demo.go b/searcher/reindex.go similarity index 67% rename from searcher/demo.go rename to searcher/reindex.go index 8ad46602..9f23b113 100644 --- a/searcher/demo.go +++ b/searcher/reindex.go @@ -3,6 +3,7 @@ package searcher import ( "context" "log" + "slices" "bridgerton.audius.co/config" "github.com/elastic/go-elasticsearch/v8" @@ -30,7 +31,7 @@ func mustDialElasticsearch() *elasticsearch.Client { return esc } -func playlistDemo(base *BaseIndexer) { +func reindexPlaylists(base *BaseIndexer) { i := &PlaylistIndexer{base} if err := i.createIndex(true); err != nil { @@ -39,11 +40,9 @@ func playlistDemo(base *BaseIndexer) { if err := i.indexAll(); err != nil { panic(err) } - - i.search("ray") } -func userDemo(base *BaseIndexer) { +func reindexUsers(base *BaseIndexer) { i := &UserIndexer{base} if err := i.createIndex(true); err != nil { @@ -52,11 +51,9 @@ func userDemo(base *BaseIndexer) { if err := i.indexAll(); err != nil { panic(err) } - - i.search("ray") } -func trackDemo(base *BaseIndexer) { +func reindexTracks(base *BaseIndexer) { i := &TrackIndexer{base} if err := i.createIndex(true); err != nil { @@ -65,11 +62,9 @@ func trackDemo(base *BaseIndexer) { if err := i.indexAll(); err != nil { panic(err) } - - i.search("rap") } -func socialDemo(base *BaseIndexer) { +func reindexSocials(base *BaseIndexer) { i := &SocialIndexer{base} if err := i.createIndex(true); err != nil { @@ -80,7 +75,7 @@ func socialDemo(base *BaseIndexer) { } } -func Demo() { +func Reindex(collections ...string) { pool := mustDialPostgres() esc := mustDialElasticsearch() @@ -89,9 +84,19 @@ func Demo() { esc, } - playlistDemo(baseIndexer) - trackDemo(baseIndexer) - userDemo(baseIndexer) - socialDemo(baseIndexer) + reindexAll := len(collections) == 0 + + if reindexAll || slices.Contains(collections, "playlists") { + reindexPlaylists(baseIndexer) + } + if reindexAll || slices.Contains(collections, "tracks") { + reindexTracks(baseIndexer) + } + if reindexAll || slices.Contains(collections, "users") { + reindexUsers(baseIndexer) + } + if reindexAll || slices.Contains(collections, "socials") { + reindexSocials(baseIndexer) + } } diff --git a/searcher/social_indexer.go b/searcher/social_indexer.go index 13a21cf3..f9983c28 100644 --- a/searcher/social_indexer.go +++ b/searcher/social_indexer.go @@ -25,6 +25,7 @@ func (ui *SocialIndexer) indexAll() error { select user_id, json_build_object ( + 'follower_count', follower_count, 'saved_track_ids', ( select @@ -81,9 +82,7 @@ func (ui *SocialIndexer) indexAll() error { ) ) as doc from - users - where - user_id < 1000 + aggregate_user users ` return ui.bulkIndexQuery("socials", sql) diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go index 8dd4bcd1..047def75 100644 --- a/searcher/track_indexer.go +++ b/searcher/track_indexer.go @@ -1,11 +1,5 @@ package searcher -import ( - "encoding/json" - "fmt" - "strings" -) - type TrackIndexer struct { *BaseIndexer } @@ -49,54 +43,7 @@ func (ti *TrackIndexer) indexAll() error { JOIN aggregate_track USING (track_id) JOIN users ON owner_id = user_id JOIN aggregate_user USING (user_id) - WHERE track_id < 100000 - LIMIT 100000` + ` return ti.bulkIndexQuery("tracks", sql) } - -func (ti *TrackIndexer) search(q string) { - query := fmt.Sprintf(`{ - "query": { - "multi_match": { - "query": %q, - "fields": ["title", "genre", "mood"] - } - } - }`, q) - - fmt.Println(query) - - res, err := ti.esc.Search( - ti.esc.Search.WithIndex("tracks"), - ti.esc.Search.WithBody(strings.NewReader(query)), - ) - if err != nil { - fmt.Println("es search error:", err) - return - } - defer res.Body.Close() - - type hit struct { - ID string `json:"_id"` - } - type hits struct { - Hits struct { - Hits []hit `json:"hits"` - } `json:"hits"` - } - - var result hits - if err := json.NewDecoder(res.Body).Decode(&result); err != nil { - fmt.Println("decode error:", err) - return - } - - var ids []string - for _, h := range result.Hits.Hits { - ids = append(ids, h.ID) - } - - fmt.Println("found ids:", ids) - -} diff --git a/searcher/user_indexer.go b/searcher/user_indexer.go index 2a227925..004ae51a 100644 --- a/searcher/user_indexer.go +++ b/searcher/user_indexer.go @@ -1,15 +1,5 @@ package searcher -import ( - "context" - "encoding/json" - "fmt" - "log" - "strings" - - "github.com/elastic/go-elasticsearch/v8/esapi" -) - /* stage: @@ -52,44 +42,7 @@ func (ui *UserIndexer) indexAll() error { ) FROM users JOIN aggregate_user USING (user_id) - LIMIT 10000` + ` return ui.bulkIndexQuery("users", sql) } - -func (ui *UserIndexer) search(q string) { - query := fmt.Sprintf(`{ - "query": { - "simple_query_string": { - "query": %q, - "default_operator": "AND" - } - } - }`, q+"*") - - req := esapi.SearchRequest{ - Index: []string{"users"}, - Body: strings.NewReader(query), - } - - res, err := req.Do(context.Background(), ui.esc) - if err != nil { - log.Fatalf("Error getting response: %s", err) - } - defer res.Body.Close() - - if res.IsError() { - log.Fatalf("Error: %s", res.String()) - } - - // Print the response body - var r map[string]interface{} - if err := json.NewDecoder(res.Body).Decode(&r); err != nil { - log.Fatalf("Error parsing the response body: %s", err) - } - - // Print the search results - for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) { - fmt.Printf("Document: %v\n", hit) - } -} diff --git a/searcher/user_search.go b/searcher/user_search.go index c7fbd810..8f044032 100644 --- a/searcher/user_search.go +++ b/searcher/user_search.go @@ -15,7 +15,7 @@ func (q *UserSearchQuery) Map() map[string]any { builder := esquery.Bool() if q.Query != "" { - builder.Must(esquery.MultiMatch(q.Query).Fields("name", "handle")) + builder.Must(esquery.MultiMatch(q.Query).Fields("name", "handle").Type(esquery.MatchTypeBoolPrefix)) } if q.MyID > 0 { From 39ea3b9df77c14f394cf38658a4c40b74d46f5b5 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Wed, 11 Jun 2025 16:16:25 -0400 Subject: [PATCH 10/30] Basic search test --- api/v1_search_autocomplete_test.go | 56 ++++++++++++++++++++++++++++++ compose.yml | 18 ++++++++++ main.go | 3 +- searcher/reindex.go | 10 ++++-- 4 files changed, 83 insertions(+), 4 deletions(-) create mode 100644 api/v1_search_autocomplete_test.go diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go new file mode 100644 index 00000000..3e93ab9e --- /dev/null +++ b/api/v1_search_autocomplete_test.go @@ -0,0 +1,56 @@ +package api + +import ( + "testing" + + "bridgerton.audius.co/searcher" + "github.com/test-go/testify/require" +) + +func TestSearch(t *testing.T) { + app := emptyTestApp(t) + + fixtures := FixtureMap{ + "users": { + { + "user_id": 1001, + "handle": "StereoSteve", + "name": "Stereo Steve", + }, + { + "user_id": 1002, + "handle": "StereoDave", + "name": "Stereo Dave", + }, + { + "user_id": 1003, + "handle": "monist", + "name": "Monist", + }, + }, + "tracks": { + { + "track_id": 1001, + "owner_id": 1001, + "title": "peanut butter jam time", + }, + }, + "follows": { + {"follower_user_id": 1001, "followee_user_id": 1002}, + }, + } + + createFixtures(app, fixtures) + + // index data to ES + searcher.Reindex(app.pool, app.esClient) + + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 2, + "data.users.0.handle": "StereoDave", + "data.users.1.handle": "StereoSteve", + }) + +} diff --git a/compose.yml b/compose.yml index c28510c5..9da5fa67 100644 --- a/compose.yml +++ b/compose.yml @@ -28,3 +28,21 @@ services: # - "log_statement=all" - "-c" - "max_connections=1000" + + elasticsearch: + image: docker.elastic.co/elasticsearch/elasticsearch:8.10.2 + container_name: elasticsearch + environment: + - network.host=0.0.0.0 + - discovery.type=single-node + - cluster.name=docker-cluster + - node.name=cluster1-node1 + - xpack.license.self_generated.type=basic + - xpack.security.enabled=false + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + ulimits: + memlock: + soft: -1 + hard: -1 + ports: + - 21400:9200 diff --git a/main.go b/main.go index 24a4d76e..459136b5 100644 --- a/main.go +++ b/main.go @@ -14,7 +14,8 @@ func main() { if len(os.Args) > 1 && os.Args[1] == "reindex" { collections := os.Args[2:] fmt.Println("reindex", collections) - searcher.Reindex(collections...) + + searcher.ReindexLegacy(collections...) return } diff --git a/searcher/reindex.go b/searcher/reindex.go index 9f23b113..095d5062 100644 --- a/searcher/reindex.go +++ b/searcher/reindex.go @@ -75,9 +75,7 @@ func reindexSocials(base *BaseIndexer) { } } -func Reindex(collections ...string) { - pool := mustDialPostgres() - esc := mustDialElasticsearch() +func Reindex(pool *pgxpool.Pool, esc *elasticsearch.Client, collections ...string) { baseIndexer := &BaseIndexer{ pool, @@ -100,3 +98,9 @@ func Reindex(collections ...string) { } } + +func ReindexLegacy(collections ...string) { + pool := mustDialPostgres() + esc := mustDialElasticsearch() + Reindex(pool, esc, collections...) +} From 9631f08593306e35ae12147fcc4871dad39f9aed Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Thu, 12 Jun 2025 16:43:11 -0400 Subject: [PATCH 11/30] test various query string filters --- api/server.go | 2 +- api/server_test.go | 1 + api/v1_search_autocomplete.go | 20 ++++- api/v1_search_autocomplete_test.go | 139 ++++++++++++++++++++++++++--- config/config.go | 2 + searcher/conn.go | 4 +- searcher/dsl_helpers.go | 2 +- searcher/dsl_test.go | 2 +- searcher/playlist_search_test.go | 1 + searcher/reindex.go | 2 +- searcher/search_and_pluck.go | 2 +- searcher/track_indexer.go | 3 + searcher/track_search.go | 33 +++++-- searcher/track_search_test.go | 1 + searcher/user_indexer.go | 1 + searcher/user_search.go | 9 +- searcher/user_search_test.go | 1 + 17 files changed, 192 insertions(+), 33 deletions(-) diff --git a/api/server.go b/api/server.go index 1a00b30e..7161e5a4 100644 --- a/api/server.go +++ b/api/server.go @@ -170,7 +170,7 @@ func NewApiServer(config config.Config) *ApiServer { panic(err) } - esClient, err := searcher.Dial() + esClient, err := searcher.Dial(config.EsUrl) if err != nil { panic(err) } diff --git a/api/server_test.go b/api/server_test.go index 81b85868..dace64f7 100644 --- a/api/server_test.go +++ b/api/server_test.go @@ -60,6 +60,7 @@ func emptyTestApp(t *testing.T) *ApiServer { app := NewApiServer(config.Config{ Env: "test", DbUrl: "postgres://postgres:example@localhost:21300/" + dbName, + EsUrl: "http://localhost:21400", DelegatePrivateKey: "0633fddb74e32b3cbc64382e405146319c11a1a52dc96598e557c5dbe2f31468", SolanaConfig: config.SolanaConfig{RpcProviders: []string{""}}, }) diff --git a/api/v1_search_autocomplete.go b/api/v1_search_autocomplete.go index a8c60e56..4e54a5e9 100644 --- a/api/v1_search_autocomplete.go +++ b/api/v1_search_autocomplete.go @@ -8,7 +8,11 @@ import ( ) func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { + // queryMap := c.Queries() + query := c.Query("query") + genres := queryMutli(c, "genre") + moods := queryMutli(c, "mood") limit := c.QueryInt("limit", 10) offset := c.QueryInt("offset", 0) @@ -23,7 +27,8 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { // users g.Go(func() error { q := searcher.UserSearchQuery{ - Query: query, + Query: query, + IsVerified: c.QueryBool("is_verified"), } dsl := searcher.BuildFunctionScoreDSL("follower_count", q.Map()) @@ -42,7 +47,16 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { // tracks g.Go(func() error { q := searcher.TrackSearchQuery{ - Query: query, + Query: query, + Genres: genres, + Moods: moods, + MinBPM: c.QueryInt("bpm_min"), + MaxBPM: c.QueryInt("bpm_max"), + MusicalKeys: queryMutli(c, "key"), + IsDownloadable: c.QueryBool("is_downloadable"), + IsPurchaseable: c.QueryBool("is_purchaseable"), + // todo: includePurchaseable + // todo: tags } dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) @@ -78,6 +92,8 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { GetPlaylistsParams: dbv1.GetPlaylistsParams{ Ids: playlistsIds, MyID: myId, + + // todo: playlist needs to support modds + genres + tags query }, }) return err diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go index 3e93ab9e..faf8f353 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_autocomplete_test.go @@ -23,16 +23,39 @@ func TestSearch(t *testing.T) { "name": "Stereo Dave", }, { - "user_id": 1003, - "handle": "monist", - "name": "Monist", + "user_id": 1003, + "handle": "monist", + "name": "Monist", + "is_verified": true, }, }, "tracks": { { - "track_id": 1001, - "owner_id": 1001, - "title": "peanut butter jam time", + "track_id": 1001, + "owner_id": 1001, + "title": "peanut butter jam time", + "genre": "Trap", + "bpm": 88, + "mood": "Defiant", + "musical_key": "A minor", + }, + { + "track_id": 1002, + "owner_id": 1001, + "title": "mouse trap", + "genre": "Trap", + "bpm": 99, + "mood": "Uplifting", + "is_downloadable": true, + "musical_key": "B minor", + }, + { + "track_id": 1003, + "owner_id": 1001, + "title": "sunny side", + "genre": "Jazz", + "mood": "Uplifting", + "stream_conditions": []byte(`{"usdc_purchase": {"price": 135, "splits": [{"user_id": 6, "percentage": 100.0}]}}`), }, }, "follows": { @@ -45,12 +68,102 @@ func TestSearch(t *testing.T) { // index data to ES searcher.Reindex(app.pool, app.esClient) - status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo") - require.Equal(t, 200, status) - jsonAssert(t, body, map[string]any{ - "data.users.#": 2, - "data.users.0.handle": "StereoDave", - "data.users.1.handle": "StereoSteve", - }) + // users: + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 2, + "data.users.0.handle": "StereoDave", + "data.users.1.handle": "StereoSteve", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?is_verified=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 1, + "data.users.0.handle": "monist", + }) + } + + // tracks: filter by genre + mood + bpm + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 2, + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&bpm_min=90") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "mouse trap", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&bpm_max=90") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "peanut butter jam time", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&genre=jazz") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 3, + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&genre=jazz&mood=uplifting") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 2, + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?is_downloadable=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "mouse trap", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?key=A+minor") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "peanut butter jam time", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?key=A+minor&key=B+minor") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 2, + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?is_purchaseable=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "sunny side", + }) + } } diff --git a/config/config.go b/config/config.go index 9a55277b..88626c6b 100644 --- a/config/config.go +++ b/config/config.go @@ -12,6 +12,7 @@ import ( type Config struct { Env string DbUrl string + EsUrl string Nodes []Node DeadNodes []string DelegatePrivateKey string @@ -28,6 +29,7 @@ type Config struct { var Cfg = Config{ Env: os.Getenv("ENV"), DbUrl: os.Getenv("discoveryDbUrl"), + EsUrl: os.Getenv("elasticsearchUrl"), DelegatePrivateKey: os.Getenv("delegatePrivateKey"), AxiomToken: os.Getenv("axiomToken"), AxiomDataset: os.Getenv("axiomDataset"), diff --git a/searcher/conn.go b/searcher/conn.go index 25d30ca1..68b3237b 100644 --- a/searcher/conn.go +++ b/searcher/conn.go @@ -2,10 +2,10 @@ package searcher import "github.com/elastic/go-elasticsearch/v8" -func Dial() (*elasticsearch.Client, error) { +func Dial(esUrl string) (*elasticsearch.Client, error) { cfg := elasticsearch.Config{ Addresses: []string{ - "http://35.238.44.255:21302", + esUrl, }, } diff --git a/searcher/dsl_helpers.go b/searcher/dsl_helpers.go index e7a1c432..008eebf2 100644 --- a/searcher/dsl_helpers.go +++ b/searcher/dsl_helpers.go @@ -43,7 +43,7 @@ func BuildFunctionScoreDSL(scoreField string, innerQuery map[string]any) string } }`, innerJson, scoreField) - pprintJson(dsl) + // pprintJson(dsl) return dsl } diff --git a/searcher/dsl_test.go b/searcher/dsl_test.go index 3e8f3cda..f0e54ee1 100644 --- a/searcher/dsl_test.go +++ b/searcher/dsl_test.go @@ -15,7 +15,7 @@ func testSearch(t *testing.T, indexName, dsl string) { pprintJson(dsl) - esClient, err := Dial() + esClient, err := Dial("http://localhost:21400") require.NoError(t, err) req := esapi.SearchRequest{ diff --git a/searcher/playlist_search_test.go b/searcher/playlist_search_test.go index 23725d20..b0709d98 100644 --- a/searcher/playlist_search_test.go +++ b/searcher/playlist_search_test.go @@ -5,6 +5,7 @@ import ( ) func TestPlaylistDsl(t *testing.T) { + t.Skip() q := &PlaylistSearchQuery{ Query: "hot", MyID: 1, diff --git a/searcher/reindex.go b/searcher/reindex.go index 095d5062..18fdea7e 100644 --- a/searcher/reindex.go +++ b/searcher/reindex.go @@ -24,7 +24,7 @@ func mustDialPostgres() *pgxpool.Pool { } func mustDialElasticsearch() *elasticsearch.Client { - esc, err := Dial() + esc, err := Dial(config.Cfg.EsUrl) if err != nil { log.Fatalf("Error creating the client: %s", err) } diff --git a/searcher/search_and_pluck.go b/searcher/search_and_pluck.go index 94cea5a0..5284345a 100644 --- a/searcher/search_and_pluck.go +++ b/searcher/search_and_pluck.go @@ -35,7 +35,7 @@ func SearchAndPluck(esClient *elasticsearch.Client, index, dsl string, limit, of return nil, err } - fmt.Println("ES BODY", index, string(body)) + // fmt.Println("ES BODY", index, string(body)) result := []int32{} for _, hit := range gjson.GetBytes(body, "hits.hits").Array() { diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go index 047def75..d68480d8 100644 --- a/searcher/track_indexer.go +++ b/searcher/track_indexer.go @@ -32,6 +32,9 @@ func (ti *TrackIndexer) indexAll() error { 'release_date', coalesce(release_date, tracks.created_at), 'musical_key', musical_key, 'bpm', bpm, + 'is_downloadable', is_downloadable, + 'download_conditions', download_conditions, + 'stream_conditions', stream_conditions, 'user', json_build_object( 'handle', users.handle, 'name', users.name, diff --git a/searcher/track_search.go b/searcher/track_search.go index e24f6479..c9779dc0 100644 --- a/searcher/track_search.go +++ b/searcher/track_search.go @@ -7,13 +7,15 @@ import ( ) type TrackSearchQuery struct { - Query string - MinBPM int - MaxBPM int - Genres []string - Moods []string - MusicalKeys []string - MyID int + Query string + MinBPM int + MaxBPM int + IsDownloadable bool + IsPurchaseable bool + Genres []string + Moods []string + MusicalKeys []string + MyID int } func (t *TrackSearchQuery) Map() map[string]any { @@ -35,17 +37,30 @@ func (t *TrackSearchQuery) Map() map[string]any { } if len(t.Genres) > 0 { - builder.Filter(esquery.Match("genre", toAnySlice(t.Genres)...)) + builder.Filter(esquery.Terms("genre", toAnySlice(t.Genres)...)) } if len(t.Moods) > 0 { - builder.Filter(esquery.Match("mood", toAnySlice(t.Moods)...)) + builder.Filter(esquery.Terms("mood", toAnySlice(t.Moods)...)) } if len(t.MusicalKeys) > 0 { builder.Filter(esquery.Terms("musical_key.keyword", toAnySlice(t.MusicalKeys)...)) } + if t.IsDownloadable { + builder.Filter(esquery.Term("is_downloadable", true)) + } + + if t.IsPurchaseable { + // stream or download + builder.Filter( + esquery.Bool(). + Should(esquery.Exists("stream_conditions.usdc_purchase")). + Should(esquery.Exists("download_conditions.usdc_purchase")), + ) + } + // boost tracks that are saved / reposted if t.MyID > 0 { builder.Should(esquery.CustomQuery(map[string]any{ diff --git a/searcher/track_search_test.go b/searcher/track_search_test.go index 6c12ed70..630df838 100644 --- a/searcher/track_search_test.go +++ b/searcher/track_search_test.go @@ -5,6 +5,7 @@ import ( ) func TestTrackDsl(t *testing.T) { + t.Skip() ts := TrackSearchQuery{ Query: "KING", diff --git a/searcher/user_indexer.go b/searcher/user_indexer.go index 004ae51a..030295bb 100644 --- a/searcher/user_indexer.go +++ b/searcher/user_indexer.go @@ -29,6 +29,7 @@ func (ui *UserIndexer) indexAll() error { 'bio', bio, 'location', location, 'created_at', created_at, + 'is_verified', is_verified, 'track_count', track_count, 'playlist_count', playlist_count, diff --git a/searcher/user_search.go b/searcher/user_search.go index 8f044032..e655c5d1 100644 --- a/searcher/user_search.go +++ b/searcher/user_search.go @@ -7,8 +7,9 @@ import ( ) type UserSearchQuery struct { - Query string `json:"query"` - MyID int `json:"my_id"` + Query string `json:"query"` + IsVerified bool `json:"is_verified"` + MyID int `json:"my_id"` } func (q *UserSearchQuery) Map() map[string]any { @@ -31,5 +32,9 @@ func (q *UserSearchQuery) Map() map[string]any { })) } + if q.IsVerified { + builder.Must(esquery.Term("is_verified", true)) + } + return builder.Map() } diff --git a/searcher/user_search_test.go b/searcher/user_search_test.go index 4ee0e84e..96272849 100644 --- a/searcher/user_search_test.go +++ b/searcher/user_search_test.go @@ -5,6 +5,7 @@ import ( ) func TestUserDsl(t *testing.T) { + t.Skip() q := &UserSearchQuery{ Query: "ray", MyID: 1, From ac48ed9e2f8086b58e8b7375ec99f69c4127c369 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Fri, 13 Jun 2025 12:28:26 -0400 Subject: [PATCH 12/30] Test that reposted tracks rank higher for current user. --- api/auth_middleware.go | 6 ++++ api/server.go | 3 ++ api/v1_search_autocomplete.go | 3 ++ api/v1_search_autocomplete_test.go | 55 ++++++++++++++++++++++++++++++ api/v1_users_search.go | 36 +++++++++++++++++++ searcher/playlist_search.go | 4 ++- searcher/track_search.go | 4 ++- searcher/user_search.go | 4 ++- 8 files changed, 112 insertions(+), 3 deletions(-) create mode 100644 api/v1_users_search.go diff --git a/api/auth_middleware.go b/api/auth_middleware.go index c6f50763..9f2aee3c 100644 --- a/api/auth_middleware.go +++ b/api/auth_middleware.go @@ -41,6 +41,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 { + + // disable auth check in test mode + if app.env == "test" { + return true + } + cacheKey := fmt.Sprintf("%d:%s", userId, authedWallet) if hit, ok := app.resolveGrantCache.Get(cacheKey); ok { return hit diff --git a/api/server.go b/api/server.go index 7161e5a4..ab62f16d 100644 --- a/api/server.go +++ b/api/server.go @@ -184,6 +184,7 @@ func NewApiServer(config config.Config) *ApiServer { ErrorHandler: errorHandler(logger), ReadBufferSize: 32_768, }), + env: config.Env, pool: pool, queries: dbv1.New(pool), logger: logger, @@ -269,6 +270,7 @@ func NewApiServer(config config.Config) *ApiServer { for _, g := range []fiber.Router{v1, v1Full} { // Users g.Get("/users", app.v1Users) + g.Get("/users/search", app.v1UsersSearch) g.Get("/users/unclaimed_id", app.v1UsersUnclaimedId) g.Get("/users/account/:wallet", app.requireAuthMiddleware, app.v1UsersAccount) @@ -434,6 +436,7 @@ type ApiServer struct { solanaConfig *config.SolanaConfig antiAbuseOracles []string validators []config.Node + env string auds *sdk.AudiusdSDK } diff --git a/api/v1_search_autocomplete.go b/api/v1_search_autocomplete.go index 4e54a5e9..25e1d998 100644 --- a/api/v1_search_autocomplete.go +++ b/api/v1_search_autocomplete.go @@ -29,6 +29,7 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { q := searcher.UserSearchQuery{ Query: query, IsVerified: c.QueryBool("is_verified"), + MyID: myId, } dsl := searcher.BuildFunctionScoreDSL("follower_count", q.Map()) @@ -57,6 +58,7 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { IsPurchaseable: c.QueryBool("is_purchaseable"), // todo: includePurchaseable // todo: tags + MyID: myId, } dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) @@ -79,6 +81,7 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { g.Go(func() error { q := searcher.PlaylistSearchQuery{ Query: query, + MyID: myId, } dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go index faf8f353..56e40b5b 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_autocomplete_test.go @@ -9,6 +9,8 @@ import ( func TestSearch(t *testing.T) { app := emptyTestApp(t) + app.env = "test" + require.Equal(t, "test", app.env) fixtures := FixtureMap{ "users": { @@ -61,6 +63,26 @@ func TestSearch(t *testing.T) { "follows": { {"follower_user_id": 1001, "followee_user_id": 1002}, }, + "reposts": { + { + "repost_item_id": 1001, + "user_id": 1001, + "repost_type": "track", + "created_at": parseTime(t, "2024-01-03"), + }, + { + "repost_item_id": 1001, + "user_id": 1002, + "repost_type": "track", + "created_at": parseTime(t, "2024-01-03"), + }, + { + "repost_item_id": 1003, + "user_id": 1003, + "repost_type": "track", + "created_at": parseTime(t, "2024-01-03"), + }, + }, } createFixtures(app, fixtures) @@ -79,6 +101,16 @@ func TestSearch(t *testing.T) { }) } + { + status, body := testGet(t, app, "/v1/users/search?query=stereo") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.#": 2, + "data.0.handle": "StereoDave", + "data.1.handle": "StereoSteve", + }) + } + { status, body := testGet(t, app, "/v1/search/autocomplete?is_verified=true") require.Equal(t, 200, status) @@ -88,6 +120,29 @@ func TestSearch(t *testing.T) { }) } + // tracks: default rank is by repost count + { + status, body := testGet(t, app, "/v1/search/autocomplete") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 3, + "data.tracks.0.title": "peanut butter jam time", + "data.tracks.0.repost_count": 2, + }) + } + + // but if you pass a user_id and have reposted a track... + // your history will rank it higher + { + status, body := testGet(t, app, "/v1/search/autocomplete?user_id=1003") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 3, + "data.tracks.0.title": "sunny side", + "data.tracks.0.repost_count": 1, + }) + } + // tracks: filter by genre + mood + bpm { status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap") diff --git a/api/v1_users_search.go b/api/v1_users_search.go new file mode 100644 index 00000000..f61cc4a1 --- /dev/null +++ b/api/v1_users_search.go @@ -0,0 +1,36 @@ +package api + +import ( + "bridgerton.audius.co/api/dbv1" + "bridgerton.audius.co/searcher" + "github.com/gofiber/fiber/v2" +) + +func (app *ApiServer) v1UsersSearch(c *fiber.Ctx) error { + myId := app.getMyId(c) + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + + q := searcher.UserSearchQuery{ + Query: c.Query("query"), + IsVerified: c.QueryBool("is_verified"), + } + + dsl := searcher.BuildFunctionScoreDSL("follower_count", q.Map()) + userIds, err := searcher.SearchAndPluck(app.esClient, "users", dsl, limit, offset) + if err != nil { + return err + } + + users, err := app.queries.FullUsers(c.Context(), dbv1.GetUsersParams{ + Ids: userIds, + MyID: myId, + }) + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": users, + }) +} diff --git a/searcher/playlist_search.go b/searcher/playlist_search.go index 98c3dd51..1aa6f20a 100644 --- a/searcher/playlist_search.go +++ b/searcher/playlist_search.go @@ -11,7 +11,7 @@ type PlaylistSearchQuery struct { Genres []string Moods []string IsAlbum bool - MyID int + MyID int32 } func (q *PlaylistSearchQuery) Map() map[string]any { @@ -19,6 +19,8 @@ func (q *PlaylistSearchQuery) Map() map[string]any { if q.Query != "" { builder.Must(esquery.Match("title", q.Query)) + } else { + builder.Must(esquery.MatchAll()) } builder.Filter(esquery.Term("is_album", q.IsAlbum)) diff --git a/searcher/track_search.go b/searcher/track_search.go index c9779dc0..382c9531 100644 --- a/searcher/track_search.go +++ b/searcher/track_search.go @@ -15,7 +15,7 @@ type TrackSearchQuery struct { Genres []string Moods []string MusicalKeys []string - MyID int + MyID int32 } func (t *TrackSearchQuery) Map() map[string]any { @@ -23,6 +23,8 @@ func (t *TrackSearchQuery) Map() map[string]any { if t.Query != "" { builder.Must(esquery.Match("title", t.Query)) + } else { + builder.Must(esquery.MatchAll()) } if t.MinBPM > 0 || t.MaxBPM > 0 { diff --git a/searcher/user_search.go b/searcher/user_search.go index e655c5d1..3ca41080 100644 --- a/searcher/user_search.go +++ b/searcher/user_search.go @@ -9,7 +9,7 @@ import ( type UserSearchQuery struct { Query string `json:"query"` IsVerified bool `json:"is_verified"` - MyID int `json:"my_id"` + MyID int32 `json:"my_id"` } func (q *UserSearchQuery) Map() map[string]any { @@ -17,6 +17,8 @@ func (q *UserSearchQuery) Map() map[string]any { if q.Query != "" { builder.Must(esquery.MultiMatch(q.Query).Fields("name", "handle").Type(esquery.MatchTypeBoolPrefix)) + } else { + builder.Must(esquery.MatchAll()) } if q.MyID > 0 { From 315e98a794c1b717e1cd0b1c9ebe24fdea11b942 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Mon, 16 Jun 2025 10:59:22 -0400 Subject: [PATCH 13/30] more explicit skipAuthCheck flag --- api/auth_middleware.go | 4 ++-- api/server.go | 1 + api/v1_search_autocomplete_test.go | 3 +-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/api/auth_middleware.go b/api/auth_middleware.go index 9f2aee3c..6dce0e2e 100644 --- a/api/auth_middleware.go +++ b/api/auth_middleware.go @@ -42,8 +42,8 @@ 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 { - // disable auth check in test mode - if app.env == "test" { + // tests can opt in to skipAuthCheck + if app.skipAuthCheck { return true } diff --git a/api/server.go b/api/server.go index ab62f16d..0783732e 100644 --- a/api/server.go +++ b/api/server.go @@ -438,6 +438,7 @@ type ApiServer struct { validators []config.Node env string auds *sdk.AudiusdSDK + skipAuthCheck bool // set to true in a test if you don't care about auth middleware } func (app *ApiServer) home(c *fiber.Ctx) error { diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go index 56e40b5b..4cb437b2 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_autocomplete_test.go @@ -9,8 +9,7 @@ import ( func TestSearch(t *testing.T) { app := emptyTestApp(t) - app.env = "test" - require.Equal(t, "test", app.env) + app.skipAuthCheck = true fixtures := FixtureMap{ "users": { From 85bc659c61b1d253f23f5e08c835313d42f40d24 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Mon, 16 Jun 2025 11:47:37 -0400 Subject: [PATCH 14/30] multi match track search + index tags. --- api/v1_search_autocomplete_test.go | 41 ++++++++++++++++++++++++++++++ searcher/track_indexer.go | 1 + searcher/track_search.go | 5 +++- 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go index 4cb437b2..3bfb548a 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_autocomplete_test.go @@ -49,6 +49,7 @@ func TestSearch(t *testing.T) { "mood": "Uplifting", "is_downloadable": true, "musical_key": "B minor", + "tags": "Tag1,Tag2,Tag3", }, { "track_id": 1003, @@ -151,6 +152,46 @@ func TestSearch(t *testing.T) { }) } + // can search artist + track title + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo+sunny") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + // "data.tracks.#": 3, + "data.tracks.0.title": "sunny side", + }) + } + + // can search tags + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=Tag2") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "mouse trap", + }) + } + + // can search artist handle + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereosteve") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 3, + "data.tracks.0.user.handle": "StereoSteve", + }) + } + + // can search artist name + if false { + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo+steve") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "sunny side", + }) + } + { status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&bpm_min=90") require.Equal(t, 200, status) diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go index d68480d8..1dfd496e 100644 --- a/searcher/track_indexer.go +++ b/searcher/track_indexer.go @@ -32,6 +32,7 @@ func (ti *TrackIndexer) indexAll() error { 'release_date', coalesce(release_date, tracks.created_at), 'musical_key', musical_key, 'bpm', bpm, + 'tags', string_to_array(tags, ','), 'is_downloadable', is_downloadable, 'download_conditions', download_conditions, 'stream_conditions', stream_conditions, diff --git a/searcher/track_search.go b/searcher/track_search.go index 382c9531..3df61b0e 100644 --- a/searcher/track_search.go +++ b/searcher/track_search.go @@ -22,7 +22,10 @@ func (t *TrackSearchQuery) Map() map[string]any { builder := esquery.Bool() if t.Query != "" { - builder.Must(esquery.Match("title", t.Query)) + builder.Must( + esquery.MultiMatch().Query(t.Query).Fields("title", "user.handle", "user.name", "tags"), + ) + } else { builder.Must(esquery.MatchAll()) } From 3e5c192c34f4238a401c482ea86805d2c18b35ee Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Mon, 16 Jun 2025 11:59:41 -0400 Subject: [PATCH 15/30] Don't index deleted / private / removed content. --- api/v1_search_autocomplete_test.go | 55 ++++++++++++++++++++++++++++++ searcher/playlist_indexer.go | 3 ++ searcher/track_indexer.go | 5 +++ searcher/user_indexer.go | 2 ++ 4 files changed, 65 insertions(+) diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go index 3bfb548a..04f00bef 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_autocomplete_test.go @@ -59,6 +59,37 @@ func TestSearch(t *testing.T) { "mood": "Uplifting", "stream_conditions": []byte(`{"usdc_purchase": {"price": 135, "splits": [{"user_id": 6, "percentage": 100.0}]}}`), }, + { + "track_id": 1004, + "owner_id": 1001, + "title": "hide deleted", + "is_delete": true, + }, + { + "track_id": 1005, + "owner_id": 1001, + "title": "hide private", + "is_unlisted": true, + }, + { + "track_id": 1006, + "owner_id": 1001, + "title": "hide unavailable", + "is_available": false, + }, + }, + "playlists": { + { + "playlist_id": 9001, + "playlist_owner_id": 1001, + "playlist_name": "Old and Busted", + }, + { + "playlist_id": 9002, + "playlist_owner_id": 1001, + "playlist_name": "My Old Album", + "is_album": true, + }, }, "follows": { {"follower_user_id": 1001, "followee_user_id": 1002}, @@ -172,6 +203,15 @@ func TestSearch(t *testing.T) { }) } + // doesn't show deleted or unlisted tracks + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=hide") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 0, + }) + } + // can search artist handle { status, body := testGet(t, app, "/v1/search/autocomplete?query=stereosteve") @@ -261,4 +301,19 @@ func TestSearch(t *testing.T) { }) } + // + // Playlists + // + + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=old") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.playlists.#": 1, + "data.playlists.0.playlist_name": "Old and Busted", + "data.albums.#": 1, + "data.albums.0.playlist_name": "My Old Album", + }) + } + } diff --git a/searcher/playlist_indexer.go b/searcher/playlist_indexer.go index d35c25af..42066007 100644 --- a/searcher/playlist_indexer.go +++ b/searcher/playlist_indexer.go @@ -42,6 +42,9 @@ func (pi *PlaylistIndexer) indexAll() error { JOIN aggregate_playlist USING (playlist_id) JOIN users ON playlist_owner_id = user_id JOIN aggregate_user USING (user_id) + WHERE is_private = false + AND users.is_available = true + AND users.is_deactivated = false ` return pi.bulkIndexQuery("playlists", sql) diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go index 1dfd496e..0e47b038 100644 --- a/searcher/track_indexer.go +++ b/searcher/track_indexer.go @@ -47,6 +47,11 @@ func (ti *TrackIndexer) indexAll() error { JOIN aggregate_track USING (track_id) JOIN users ON owner_id = user_id JOIN aggregate_user USING (user_id) + WHERE tracks.is_unlisted = false + AND tracks.is_delete = false + AND tracks.is_available = true + AND users.is_available = true + AND users.is_deactivated = false ` return ti.bulkIndexQuery("tracks", sql) diff --git a/searcher/user_indexer.go b/searcher/user_indexer.go index 030295bb..a735169b 100644 --- a/searcher/user_indexer.go +++ b/searcher/user_indexer.go @@ -43,6 +43,8 @@ func (ui *UserIndexer) indexAll() error { ) FROM users JOIN aggregate_user USING (user_id) + WHERE is_deactivated = false + AND is_available = true ` return ui.bulkIndexQuery("users", sql) From 2d05f55f900a224829a8fb39414269f7184cf655 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Tue, 17 Jun 2025 13:15:25 -0400 Subject: [PATCH 16/30] wip: incremental indexing --- api/v1_search_autocomplete_test.go | 2 +- main.go | 6 +++-- searcher/base_indexer.go | 43 +++++++++++++++++++++++++++--- searcher/playlist_indexer.go | 11 +++++--- searcher/reindex.go | 15 ++++++----- searcher/social_indexer.go | 13 ++++++--- searcher/track_indexer.go | 10 +++++-- searcher/user_indexer.go | 10 +++++-- 8 files changed, 87 insertions(+), 23 deletions(-) diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go index 04f00bef..6eba535e 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_autocomplete_test.go @@ -119,7 +119,7 @@ func TestSearch(t *testing.T) { createFixtures(app, fixtures) // index data to ES - searcher.Reindex(app.pool, app.esClient) + searcher.Reindex(app.pool, app.esClient, true) // users: { diff --git a/main.go b/main.go index 459136b5..ee26beca 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "fmt" "os" + "slices" "bridgerton.audius.co/api" "bridgerton.audius.co/config" @@ -13,9 +14,10 @@ func main() { if len(os.Args) > 1 && os.Args[1] == "reindex" { collections := os.Args[2:] - fmt.Println("reindex", collections) + drop := slices.Contains(collections, "drop") + fmt.Println("reindex", "drop", drop, "collections", collections) - searcher.ReindexLegacy(collections...) + searcher.ReindexLegacy(drop, collections...) return } diff --git a/searcher/base_indexer.go b/searcher/base_indexer.go index dbb48411..6dbf5a1b 100644 --- a/searcher/base_indexer.go +++ b/searcher/base_indexer.go @@ -3,21 +3,24 @@ package searcher import ( "context" "fmt" + "io" "log" "strings" "github.com/elastic/go-elasticsearch/v8" "github.com/elastic/go-elasticsearch/v8/esutil" "github.com/jackc/pgx/v5/pgxpool" + "github.com/tidwall/gjson" ) type BaseIndexer struct { pool *pgxpool.Pool esc *elasticsearch.Client + drop bool } -func (base *BaseIndexer) createIndex(indexName string, mapping string, drop bool) error { - if drop { +func (base *BaseIndexer) createIndex(indexName string, mapping string) error { + if base.drop { _, err := base.esc.Indices.Delete([]string{indexName}) if err != nil { fmt.Println("drop error", indexName, err) @@ -40,6 +43,40 @@ func (base *BaseIndexer) createIndex(indexName string, mapping string, drop bool } func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { + + // Get the max updated_at from the Elasticsearch index + var maxBlocknumber int64 + + { + + res, err := base.esc.Search( + base.esc.Search.WithIndex(index), + base.esc.Search.WithBody(strings.NewReader(`{ + "size": 0, + "aggs": { + "max_blocknumber": { + "max": { + "field": "blocknumber" + } + } + } + }`)), + base.esc.Search.WithTrackTotalHits(false), + ) + if err != nil { + fmt.Println("error querying max_blocknumber:", err) + return err + } + defer res.Body.Close() + + body, _ := io.ReadAll(res.Body) + maxBlocknumber = gjson.GetBytes(body, "aggregations.max_blocknumber.value").Int() + + pprintJson(string(body)) + fmt.Println("________ maxBlocknumber", maxBlocknumber) + + } + ctx := context.Background() bulk, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{ Index: index, @@ -51,7 +88,7 @@ func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { log.Fatalf("Error creating the indexer: %s", err) } - rows, err := base.pool.Query(ctx, sql) + rows, err := base.pool.Query(ctx, sql, maxBlocknumber) if err != nil { return err } diff --git a/searcher/playlist_indexer.go b/searcher/playlist_indexer.go index 42066007..ccf6c23a 100644 --- a/searcher/playlist_indexer.go +++ b/searcher/playlist_indexer.go @@ -4,7 +4,7 @@ type PlaylistIndexer struct { *BaseIndexer } -func (pi *PlaylistIndexer) createIndex(drop bool) error { +func (pi *PlaylistIndexer) createIndex() error { // Specify mappings for playlist index // Only specifying properties that might be ambiguous mapping := `{ @@ -13,7 +13,7 @@ func (pi *PlaylistIndexer) createIndex(drop bool) error { } } }` - return pi.BaseIndexer.createIndex("playlists", mapping, drop) + return pi.BaseIndexer.createIndex("playlists", mapping) } func (pi *PlaylistIndexer) indexAll() error { @@ -27,8 +27,9 @@ func (pi *PlaylistIndexer) indexAll() error { 'track_count', track_count, 'save_count', aggregate_playlist.save_count, 'repost_count', aggregate_playlist.repost_count, - 'last_updated', playlists.updated_at, 'created_at', playlists.created_at, + 'updated_at', playlists.updated_at, + 'blocknumber', playlists.blocknumber, 'is_private', is_private, 'is_album', playlists.is_album, 'user', json_build_object( @@ -45,6 +46,10 @@ func (pi *PlaylistIndexer) indexAll() error { WHERE is_private = false AND users.is_available = true AND users.is_deactivated = false + AND playlists.blocknumber > $1 + ORDER BY playlists.blocknumber ASC + + -- LIMIT 1000 ` return pi.bulkIndexQuery("playlists", sql) diff --git a/searcher/reindex.go b/searcher/reindex.go index 18fdea7e..b23d0ac5 100644 --- a/searcher/reindex.go +++ b/searcher/reindex.go @@ -34,7 +34,7 @@ func mustDialElasticsearch() *elasticsearch.Client { func reindexPlaylists(base *BaseIndexer) { i := &PlaylistIndexer{base} - if err := i.createIndex(true); err != nil { + if err := i.createIndex(); err != nil { panic(err) } if err := i.indexAll(); err != nil { @@ -45,7 +45,7 @@ func reindexPlaylists(base *BaseIndexer) { func reindexUsers(base *BaseIndexer) { i := &UserIndexer{base} - if err := i.createIndex(true); err != nil { + if err := i.createIndex(); err != nil { panic(err) } if err := i.indexAll(); err != nil { @@ -56,7 +56,7 @@ func reindexUsers(base *BaseIndexer) { func reindexTracks(base *BaseIndexer) { i := &TrackIndexer{base} - if err := i.createIndex(true); err != nil { + if err := i.createIndex(); err != nil { panic(err) } if err := i.indexAll(); err != nil { @@ -67,7 +67,7 @@ func reindexTracks(base *BaseIndexer) { func reindexSocials(base *BaseIndexer) { i := &SocialIndexer{base} - if err := i.createIndex(true); err != nil { + if err := i.createIndex(); err != nil { panic(err) } if err := i.indexAll(); err != nil { @@ -75,11 +75,12 @@ func reindexSocials(base *BaseIndexer) { } } -func Reindex(pool *pgxpool.Pool, esc *elasticsearch.Client, collections ...string) { +func Reindex(pool *pgxpool.Pool, esc *elasticsearch.Client, drop bool, collections ...string) { baseIndexer := &BaseIndexer{ pool, esc, + drop, } reindexAll := len(collections) == 0 @@ -99,8 +100,8 @@ func Reindex(pool *pgxpool.Pool, esc *elasticsearch.Client, collections ...strin } -func ReindexLegacy(collections ...string) { +func ReindexLegacy(drop bool, collections ...string) { pool := mustDialPostgres() esc := mustDialElasticsearch() - Reindex(pool, esc, collections...) + Reindex(pool, esc, drop, collections...) } diff --git a/searcher/social_indexer.go b/searcher/social_indexer.go index f9983c28..41673914 100644 --- a/searcher/social_indexer.go +++ b/searcher/social_indexer.go @@ -5,7 +5,7 @@ type SocialIndexer struct { *BaseIndexer } -func (ui *SocialIndexer) createIndex(drop bool) error { +func (ui *SocialIndexer) createIndex() error { mapping := `{ "mappings": { "properties": { @@ -17,7 +17,7 @@ func (ui *SocialIndexer) createIndex(drop bool) error { } } }` - return ui.BaseIndexer.createIndex("socials", mapping, drop) + return ui.BaseIndexer.createIndex("socials", mapping) } func (ui *SocialIndexer) indexAll() error { @@ -25,7 +25,7 @@ func (ui *SocialIndexer) indexAll() error { select user_id, json_build_object ( - 'follower_count', follower_count, + 'follower_count', follower_count, 'saved_track_ids', ( select @@ -83,6 +83,13 @@ func (ui *SocialIndexer) indexAll() error { ) as doc from aggregate_user users + + -- normally blocknumber ($1) would be used as indexing cursor + -- but atm there's no way to do the social index incrementally + -- so do this to use the $1 parameter + WHERE -1 < $1 + + LIMIT 1000 ` return ui.bulkIndexQuery("socials", sql) diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go index 0e47b038..d09edf02 100644 --- a/searcher/track_indexer.go +++ b/searcher/track_indexer.go @@ -4,7 +4,7 @@ type TrackIndexer struct { *BaseIndexer } -func (ti *TrackIndexer) createIndex(drop bool) error { +func (ti *TrackIndexer) createIndex() error { // we rely on elasticsearch dynamic mapping // so we only need to specify properties that might be ambigious (int vs float) mapping := `{ @@ -14,7 +14,7 @@ func (ti *TrackIndexer) createIndex(drop bool) error { } } }` - return ti.BaseIndexer.createIndex("tracks", mapping, drop) + return ti.BaseIndexer.createIndex("tracks", mapping) } func (ti *TrackIndexer) indexAll() error { @@ -30,6 +30,8 @@ func (ti *TrackIndexer) indexAll() error { 'repost_count', aggregate_track.repost_count, 'comment_count', aggregate_track.comment_count, 'release_date', coalesce(release_date, tracks.created_at), + 'updated_at', tracks.updated_at, + 'blocknumber', tracks.blocknumber, 'musical_key', musical_key, 'bpm', bpm, 'tags', string_to_array(tags, ','), @@ -52,6 +54,10 @@ func (ti *TrackIndexer) indexAll() error { AND tracks.is_available = true AND users.is_available = true AND users.is_deactivated = false + AND tracks.blocknumber > $1 + ORDER BY tracks.blocknumber ASC + + -- LIMIT 1000 ` return ti.bulkIndexQuery("tracks", sql) diff --git a/searcher/user_indexer.go b/searcher/user_indexer.go index a735169b..ffed1605 100644 --- a/searcher/user_indexer.go +++ b/searcher/user_indexer.go @@ -14,9 +14,9 @@ type UserIndexer struct { *BaseIndexer } -func (ui *UserIndexer) createIndex(drop bool) error { +func (ui *UserIndexer) createIndex() error { mapping := `` - return ui.BaseIndexer.createIndex("users", mapping, drop) + return ui.BaseIndexer.createIndex("users", mapping) } func (ui *UserIndexer) indexAll() error { @@ -29,6 +29,8 @@ func (ui *UserIndexer) indexAll() error { 'bio', bio, 'location', location, 'created_at', created_at, + 'updated_at', updated_at, + 'blocknumber', users.blocknumber, 'is_verified', is_verified, 'track_count', track_count, @@ -45,6 +47,10 @@ func (ui *UserIndexer) indexAll() error { JOIN aggregate_user USING (user_id) WHERE is_deactivated = false AND is_available = true + AND blocknumber > $1 + ORDER BY users.blocknumber ASC + + -- LIMIT 1000 ` return ui.bulkIndexQuery("users", sql) From 5778b791b71813065164606adb647b96bc1edc6d Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Tue, 17 Jun 2025 16:46:06 -0400 Subject: [PATCH 17/30] honor kind + only_verified params. Playlist has track stubs --- api/fixture_test.go | 10 +++++++-- api/server.go | 4 ++++ api/v1_search_autocomplete.go | 31 +++++++++++++++++++++----- api/v1_search_autocomplete_test.go | 35 ++++++++++++++++++++++++++++-- searcher/base_indexer.go | 2 +- searcher/dsl_helpers.go | 2 +- searcher/playlist_indexer.go | 26 +++++++++++++++++++++- searcher/playlist_search.go | 17 ++++++++++----- searcher/track_indexer.go | 4 +++- searcher/track_search.go | 8 +++++++ 10 files changed, 120 insertions(+), 19 deletions(-) diff --git a/api/fixture_test.go b/api/fixture_test.go index a66a683d..da894845 100644 --- a/api/fixture_test.go +++ b/api/fixture_test.go @@ -12,6 +12,7 @@ import ( var ( baseRows = map[string]map[string]any{ "users": { + "blocknumber": 101, "user_id": nil, "handle": nil, "handle_lc": nil, @@ -29,6 +30,7 @@ var ( "profile_type": nil, }, "tracks": { + "blocknumber": 101, "blockhash": "block_abc123", "track_id": "@track_id", "is_current": true, @@ -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": "{}", @@ -195,6 +196,11 @@ var ( "blocknumber": 101, "txhash": "tx123", }, + "playlist_tracks": { + "created_at": time.Now(), + "updated_at": time.Now(), + "is_removed": false, + }, "comments": { "entity_type": "Track", "created_at": time.Now(), diff --git a/api/server.go b/api/server.go index 0783732e..8ce06daa 100644 --- a/api/server.go +++ b/api/server.go @@ -177,6 +177,8 @@ func NewApiServer(config config.Config) *ApiServer { auds := sdk.NewAudiusdSDK(config.AudiusdURL) + skipAuthCheck, _ := strconv.ParseBool(os.Getenv("skipAuthCheck")) + app := &ApiServer{ App: fiber.New(fiber.Config{ JSONEncoder: json.Marshal, @@ -185,6 +187,7 @@ func NewApiServer(config config.Config) *ApiServer { ReadBufferSize: 32_768, }), env: config.Env, + skipAuthCheck: skipAuthCheck, pool: pool, queries: dbv1.New(pool), logger: logger, @@ -339,6 +342,7 @@ func NewApiServer(config config.Config) *ApiServer { // Search g.Get("/search/autocomplete", app.v1SearchAutocomplete) + g.Get("/search/full", app.v1SearchAutocomplete) // Developer Apps g.Get("/developer_apps/:address", app.v1DeveloperApps) diff --git a/api/v1_search_autocomplete.go b/api/v1_search_autocomplete.go index 25e1d998..033f8070 100644 --- a/api/v1_search_autocomplete.go +++ b/api/v1_search_autocomplete.go @@ -10,6 +10,7 @@ import ( func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { // queryMap := c.Queries() + kind := c.Query("kind", "all") query := c.Query("query") genres := queryMutli(c, "genre") moods := queryMutli(c, "mood") @@ -19,13 +20,17 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { myId := app.getMyId(c) g := errgroup.Group{} - var users []dbv1.FullUser - var tracks []dbv1.FullTrack - var playlists []dbv1.FullPlaylist - var albums []dbv1.FullPlaylist + var users = []dbv1.FullUser{} + var tracks = []dbv1.FullTrack{} + var playlists = []dbv1.FullPlaylist{} + var albums = []dbv1.FullPlaylist{} // users g.Go(func() error { + if kind != "all" && kind != "users" { + return nil + } + q := searcher.UserSearchQuery{ Query: query, IsVerified: c.QueryBool("is_verified"), @@ -47,6 +52,10 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { // tracks g.Go(func() error { + if kind != "all" && kind != "tracks" { + return nil + } + q := searcher.TrackSearchQuery{ Query: query, Genres: genres, @@ -56,6 +65,7 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { MusicalKeys: queryMutli(c, "key"), IsDownloadable: c.QueryBool("is_downloadable"), IsPurchaseable: c.QueryBool("is_purchaseable"), + OnlyVerified: c.QueryBool("only_verified"), // todo: includePurchaseable // todo: tags MyID: myId, @@ -79,9 +89,14 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { // playlists g.Go(func() error { + if kind != "all" && kind != "playlists" { + return nil + } + q := searcher.PlaylistSearchQuery{ - Query: query, - MyID: myId, + Query: query, + MyID: myId, + OnlyVerified: c.QueryBool("only_verified"), } dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) @@ -104,6 +119,10 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { // albums g.Go(func() error { + if kind != "all" && kind != "albums" { + return nil + } + q := searcher.PlaylistSearchQuery{ Query: query, IsAlbum: true, diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go index 6eba535e..a05cdf0b 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_autocomplete_test.go @@ -77,6 +77,11 @@ func TestSearch(t *testing.T) { "title": "hide unavailable", "is_available": false, }, + { + "track_id": 1007, + "owner_id": 1003, + "title": "circular thoughts", + }, }, "playlists": { { @@ -90,6 +95,17 @@ func TestSearch(t *testing.T) { "playlist_name": "My Old Album", "is_album": true, }, + { + "playlist_id": 9003, + "playlist_owner_id": 1001, + "playlist_name": "Hot and New", + }, + }, + "playlist_tracks": { + { + "playlist_id": 9003, + "track_id": 1007, + }, }, "follows": { {"follower_user_id": 1001, "followee_user_id": 1002}, @@ -156,7 +172,6 @@ func TestSearch(t *testing.T) { status, body := testGet(t, app, "/v1/search/autocomplete") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ - "data.tracks.#": 3, "data.tracks.0.title": "peanut butter jam time", "data.tracks.0.repost_count": 2, }) @@ -168,7 +183,6 @@ func TestSearch(t *testing.T) { status, body := testGet(t, app, "/v1/search/autocomplete?user_id=1003") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ - "data.tracks.#": 3, "data.tracks.0.title": "sunny side", "data.tracks.0.repost_count": 1, }) @@ -183,6 +197,15 @@ func TestSearch(t *testing.T) { }) } + // tracks: only verified + { + status, body := testGet(t, app, "/v1/search/autocomplete?only_verified=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.0.title": "circular thoughts", + }) + } + // can search artist + track title { status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo+sunny") @@ -316,4 +339,12 @@ func TestSearch(t *testing.T) { }) } + { + status, body := testGet(t, app, "/v1/search/autocomplete?only_verified=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.playlists.0.playlist_name": "Hot and New", + }) + } + } diff --git a/searcher/base_indexer.go b/searcher/base_indexer.go index 6dbf5a1b..b0e78194 100644 --- a/searcher/base_indexer.go +++ b/searcher/base_indexer.go @@ -47,7 +47,7 @@ func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { // Get the max updated_at from the Elasticsearch index var maxBlocknumber int64 - { + if false { res, err := base.esc.Search( base.esc.Search.WithIndex(index), diff --git a/searcher/dsl_helpers.go b/searcher/dsl_helpers.go index 008eebf2..2c8edd8c 100644 --- a/searcher/dsl_helpers.go +++ b/searcher/dsl_helpers.go @@ -33,7 +33,7 @@ func BuildFunctionScoreDSL(scoreField string, innerQuery map[string]any) string { "field_value_factor": { "field": %q, - "factor": 1, + "factor": 100, "modifier": "log1p", "missing": 0 } diff --git a/searcher/playlist_indexer.go b/searcher/playlist_indexer.go index ccf6c23a..173b4919 100644 --- a/searcher/playlist_indexer.go +++ b/searcher/playlist_indexer.go @@ -36,7 +36,31 @@ func (pi *PlaylistIndexer) indexAll() error { 'handle', users.handle, 'name', users.name, 'location', users.location, - 'follower_count', aggregate_user.follower_count + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified + ), + 'tracks', ( + SELECT json_agg( + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'tags', string_to_array(tags, ','), + + -- todo: more track fields + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified + ) + ) + ) + FROM playlist_tracks + JOIN tracks USING (track_id) + JOIN users ON owner_id = user_id + WHERE playlist_id = playlists.playlist_id ) ) FROM playlists diff --git a/searcher/playlist_search.go b/searcher/playlist_search.go index 1aa6f20a..0ccb07bf 100644 --- a/searcher/playlist_search.go +++ b/searcher/playlist_search.go @@ -7,11 +7,12 @@ import ( ) type PlaylistSearchQuery struct { - Query string - Genres []string - Moods []string - IsAlbum bool - MyID int32 + Query string + Genres []string + Moods []string + IsAlbum bool + OnlyVerified bool + MyID int32 } func (q *PlaylistSearchQuery) Map() map[string]any { @@ -38,5 +39,11 @@ func (q *PlaylistSearchQuery) Map() map[string]any { })) } + // todo: mood, genre, tags + + if q.OnlyVerified { + builder.Must(esquery.Term("tracks.user.is_verified", true)) + } + return builder.Map() } diff --git a/searcher/track_indexer.go b/searcher/track_indexer.go index d09edf02..7f51a91e 100644 --- a/searcher/track_indexer.go +++ b/searcher/track_indexer.go @@ -36,13 +36,15 @@ func (ti *TrackIndexer) indexAll() error { 'bpm', bpm, 'tags', string_to_array(tags, ','), 'is_downloadable', is_downloadable, + 'has_stems', (select true from stems where parent_track_id = tracks.track_id limit 1), 'download_conditions', download_conditions, 'stream_conditions', stream_conditions, 'user', json_build_object( 'handle', users.handle, 'name', users.name, 'location', users.location, - 'follower_count', aggregate_user.follower_count + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified ) ) FROM tracks diff --git a/searcher/track_search.go b/searcher/track_search.go index 3df61b0e..0eeb112b 100644 --- a/searcher/track_search.go +++ b/searcher/track_search.go @@ -12,6 +12,7 @@ type TrackSearchQuery struct { MaxBPM int IsDownloadable bool IsPurchaseable bool + OnlyVerified bool Genres []string Moods []string MusicalKeys []string @@ -57,6 +58,9 @@ func (t *TrackSearchQuery) Map() map[string]any { builder.Filter(esquery.Term("is_downloadable", true)) } + // todo: only_with_downloads + // => downloadable + has stems + if t.IsPurchaseable { // stream or download builder.Filter( @@ -66,6 +70,10 @@ func (t *TrackSearchQuery) Map() map[string]any { ) } + if t.OnlyVerified { + builder.Must(esquery.Term("user.is_verified", true)) + } + // boost tracks that are saved / reposted if t.MyID > 0 { builder.Should(esquery.CustomQuery(map[string]any{ From 8dc50d6f8336e4ab740defae647874ff58f518a8 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Wed, 18 Jun 2025 12:57:13 -0400 Subject: [PATCH 18/30] tag search endpoint --- api/server.go | 1 + api/v1_search_autocomplete.go | 19 +++++++++----- api/v1_search_autocomplete_test.go | 28 +++++++++++++++++++- searcher/playlist_search.go | 7 +++-- searcher/track_search.go | 42 ++++++++++++++++-------------- searcher/user_indexer.go | 17 +++++++++++- searcher/user_search.go | 11 +++++--- 7 files changed, 91 insertions(+), 34 deletions(-) diff --git a/api/server.go b/api/server.go index 8ce06daa..7bd36a4f 100644 --- a/api/server.go +++ b/api/server.go @@ -343,6 +343,7 @@ func NewApiServer(config config.Config) *ApiServer { // Search g.Get("/search/autocomplete", app.v1SearchAutocomplete) g.Get("/search/full", app.v1SearchAutocomplete) + g.Get("/search/tags", app.v1SearchAutocomplete) // Developer Apps g.Get("/developer_apps/:address", app.v1DeveloperApps) diff --git a/api/v1_search_autocomplete.go b/api/v1_search_autocomplete.go index 033f8070..dc8c5219 100644 --- a/api/v1_search_autocomplete.go +++ b/api/v1_search_autocomplete.go @@ -1,6 +1,8 @@ package api import ( + "strings" + "bridgerton.audius.co/api/dbv1" "bridgerton.audius.co/searcher" "github.com/gofiber/fiber/v2" @@ -8,7 +10,8 @@ import ( ) func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { - // queryMap := c.Queries() + + isTagSearch := strings.Contains(c.Route().Path, "search/tags") kind := c.Query("kind", "all") query := c.Query("query") @@ -32,9 +35,10 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { } q := searcher.UserSearchQuery{ - Query: query, - IsVerified: c.QueryBool("is_verified"), - MyID: myId, + Query: query, + IsVerified: c.QueryBool("is_verified"), + IsTagSearch: isTagSearch, + MyID: myId, } dsl := searcher.BuildFunctionScoreDSL("follower_count", q.Map()) @@ -66,9 +70,11 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { IsDownloadable: c.QueryBool("is_downloadable"), IsPurchaseable: c.QueryBool("is_purchaseable"), OnlyVerified: c.QueryBool("only_verified"), + // todo: includePurchaseable - // todo: tags - MyID: myId, + + IsTagSearch: isTagSearch, + MyID: myId, } dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) @@ -97,6 +103,7 @@ func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { Query: query, MyID: myId, OnlyVerified: c.QueryBool("only_verified"), + IsTagSearch: isTagSearch, } dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_autocomplete_test.go index a05cdf0b..ab014b54 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_autocomplete_test.go @@ -148,6 +148,17 @@ func TestSearch(t *testing.T) { }) } + // users: prefix match + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=ster") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 2, + "data.users.0.handle": "StereoDave", + "data.users.1.handle": "StereoSteve", + }) + } + { status, body := testGet(t, app, "/v1/users/search?query=stereo") require.Equal(t, 200, status) @@ -208,7 +219,7 @@ func TestSearch(t *testing.T) { // can search artist + track title { - status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo+sunny") + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo+sun") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ // "data.tracks.#": 3, @@ -347,4 +358,19 @@ func TestSearch(t *testing.T) { }) } + // + // tag search + // + + // users: + { + status, body := testGet(t, app, "/v1/search/tags?query=Tag2") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 1, + "data.users.0.handle": "StereoSteve", + "data.tracks.#": 1, + "data.tracks.0.title": "mouse trap", + }) + } } diff --git a/searcher/playlist_search.go b/searcher/playlist_search.go index 0ccb07bf..c771574b 100644 --- a/searcher/playlist_search.go +++ b/searcher/playlist_search.go @@ -10,6 +10,7 @@ type PlaylistSearchQuery struct { Query string Genres []string Moods []string + IsTagSearch bool IsAlbum bool OnlyVerified bool MyID int32 @@ -18,8 +19,10 @@ type PlaylistSearchQuery struct { func (q *PlaylistSearchQuery) Map() map[string]any { builder := esquery.Bool() - if q.Query != "" { - builder.Must(esquery.Match("title", q.Query)) + 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", "user.handle", "user.name").Type(esquery.MatchTypeBoolPrefix)) } else { builder.Must(esquery.MatchAll()) } diff --git a/searcher/track_search.go b/searcher/track_search.go index 0eeb112b..97192124 100644 --- a/searcher/track_search.go +++ b/searcher/track_search.go @@ -12,6 +12,7 @@ type TrackSearchQuery struct { MaxBPM int IsDownloadable bool IsPurchaseable bool + IsTagSearch bool OnlyVerified bool Genres []string Moods []string @@ -19,49 +20,50 @@ type TrackSearchQuery struct { MyID int32 } -func (t *TrackSearchQuery) Map() map[string]any { +func (q *TrackSearchQuery) Map() map[string]any { builder := esquery.Bool() - if t.Query != "" { + if q.IsTagSearch { + builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tags").Type(esquery.MatchTypeBoolPrefix)) + } else if q.Query != "" { builder.Must( - esquery.MultiMatch().Query(t.Query).Fields("title", "user.handle", "user.name", "tags"), + esquery.MultiMatch().Query(q.Query).Fields("title", "user.handle", "user.name", "tags").Type(esquery.MatchTypeBoolPrefix), ) - } else { builder.Must(esquery.MatchAll()) } - if t.MinBPM > 0 || t.MaxBPM > 0 { + if q.MinBPM > 0 || q.MaxBPM > 0 { bpmRange := esquery.Range("bpm") - if t.MinBPM > 0 { - bpmRange.Gte(t.MinBPM) + if q.MinBPM > 0 { + bpmRange.Gte(q.MinBPM) } - if t.MaxBPM > 0 { - bpmRange.Lte(t.MaxBPM) + if q.MaxBPM > 0 { + bpmRange.Lte(q.MaxBPM) } builder.Filter(bpmRange) } - if len(t.Genres) > 0 { - builder.Filter(esquery.Terms("genre", toAnySlice(t.Genres)...)) + if len(q.Genres) > 0 { + builder.Filter(esquery.Terms("genre", toAnySlice(q.Genres)...)) } - if len(t.Moods) > 0 { - builder.Filter(esquery.Terms("mood", toAnySlice(t.Moods)...)) + if len(q.Moods) > 0 { + builder.Filter(esquery.Terms("mood", toAnySlice(q.Moods)...)) } - if len(t.MusicalKeys) > 0 { - builder.Filter(esquery.Terms("musical_key.keyword", toAnySlice(t.MusicalKeys)...)) + if len(q.MusicalKeys) > 0 { + builder.Filter(esquery.Terms("musical_key.keyword", toAnySlice(q.MusicalKeys)...)) } - if t.IsDownloadable { + if q.IsDownloadable { builder.Filter(esquery.Term("is_downloadable", true)) } // todo: only_with_downloads // => downloadable + has stems - if t.IsPurchaseable { + if q.IsPurchaseable { // stream or download builder.Filter( esquery.Bool(). @@ -70,17 +72,17 @@ func (t *TrackSearchQuery) Map() map[string]any { ) } - if t.OnlyVerified { + if q.OnlyVerified { builder.Must(esquery.Term("user.is_verified", true)) } // boost tracks that are saved / reposted - if t.MyID > 0 { + 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", t.MyID), + "id": fmt.Sprintf("%d", q.MyID), "path": "reposted_track_ids", }, "boost": 10, diff --git a/searcher/user_indexer.go b/searcher/user_indexer.go index ffed1605..554a3238 100644 --- a/searcher/user_indexer.go +++ b/searcher/user_indexer.go @@ -41,7 +41,22 @@ func (ui *UserIndexer) indexAll() error { 'supporter_count', supporter_count, 'supporting_count', supporting_count, 'dominant_genre', dominant_genre, - 'dominant_genre_count', dominant_genre_count + 'dominant_genre_count', dominant_genre_count, + + 'tracks', ( + SELECT json_agg( + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'tags', string_to_array(tags, ',') + + -- todo: more track fields + ) + ) + FROM tracks + WHERE owner_id = users.user_id + ) ) FROM users JOIN aggregate_user USING (user_id) diff --git a/searcher/user_search.go b/searcher/user_search.go index 3ca41080..4fa43d6f 100644 --- a/searcher/user_search.go +++ b/searcher/user_search.go @@ -7,15 +7,18 @@ import ( ) type UserSearchQuery struct { - Query string `json:"query"` - IsVerified bool `json:"is_verified"` - MyID int32 `json:"my_id"` + Query string `json:"query"` + IsVerified bool `json:"is_verified"` + IsTagSearch bool + MyID int32 `json:"my_id"` } func (q *UserSearchQuery) Map() map[string]any { builder := esquery.Bool() - if q.Query != "" { + if q.IsTagSearch { + builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tracks.tags").Type(esquery.MatchTypeBoolPrefix)) + } else if q.Query != "" { builder.Must(esquery.MultiMatch(q.Query).Fields("name", "handle").Type(esquery.MatchTypeBoolPrefix)) } else { builder.Must(esquery.MatchAll()) From 5c3ee610b8b558284cad0669fb0742aa590d13a9 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Wed, 18 Jun 2025 16:34:59 -0400 Subject: [PATCH 19/30] example of LISTEN for NOTIFY events. so indexer can mimic es-indexer typescript behavior. --- go.mod | 5 +++ go.sum | 15 +++++++++ searcher/listen_demo/listen.go | 56 ++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 searcher/listen_demo/listen.go diff --git a/go.mod b/go.mod index 033251af..ee284643 100644 --- a/go.mod +++ b/go.mod @@ -16,8 +16,10 @@ require ( github.com/go-playground/validator/v10 v10.26.0 github.com/gofiber/contrib/fiberzap/v2 v2.1.5 github.com/gofiber/fiber/v2 v2.52.6 + github.com/jackc/pgconn v1.14.3 github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f github.com/jackc/pgx/v5 v5.7.4 + github.com/jackc/pgxlisten v0.0.0-20241106001234-1d6f6656415c github.com/joho/godotenv v1.5.1 github.com/maypok86/otter v1.2.4 github.com/mcuadros/go-defaults v1.2.0 @@ -104,7 +106,10 @@ require ( github.com/gorilla/websocket v1.5.3 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect github.com/holiman/uint256 v1.3.2 // indirect + github.com/jackc/chunkreader/v2 v2.0.1 // indirect + github.com/jackc/pgio v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgproto3/v2 v2.3.3 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jmhodges/levigo v1.0.0 // indirect diff --git a/go.sum b/go.sum index 5e48c1f2..40fb42b7 100644 --- a/go.sum +++ b/go.sum @@ -227,14 +227,27 @@ github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyf github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA= github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= +github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/pgconn v1.14.3 h1:bVoTr12EGANZz66nZPkMInAV/KHD2TxH9npjXXgiB3w= +github.com/jackc/pgconn v1.14.3/go.mod h1:RZbme4uasqzybK2RK5c65VsHxoyaml09lx3tXOcO/VM= +github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= +github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUOag= +github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f h1:ahoGnXfh4wiCisojvzq1PzgxzFwJEUHMI26pUY6oluk= github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f/go.mod h1:m9tCxmy1PSUQa5o0aL4rQTowmJD1BK2Zc7dgnK/IrXc= github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= +github.com/jackc/pgxlisten v0.0.0-20241106001234-1d6f6656415c h1:bTgmg761ac9Ki27HoLx8IBvc+T+Qj6eptBpKahKIRT4= +github.com/jackc/pgxlisten v0.0.0-20241106001234-1d6f6656415c/go.mod h1:N4E1APLOYrbM11HH5kdqAjDa8RJWVwD3JqWpvH22h64= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jgroeneveld/schema v1.0.0 h1:J0E10CrOkiSEsw6dfb1IfrDJD14pf6QLVJ3tRPl/syI= @@ -368,6 +381,7 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -575,6 +589,7 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/searcher/listen_demo/listen.go b/searcher/listen_demo/listen.go new file mode 100644 index 00000000..14b3baa1 --- /dev/null +++ b/searcher/listen_demo/listen.go @@ -0,0 +1,56 @@ +package main + +import ( + "context" + "fmt" + "log" + "os" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgxlisten" + + _ "github.com/joho/godotenv/autoload" +) + +func main() { + ctx := context.Background() + + listener := &pgxlisten.Listener{ + // Provide a pgx connection for listening + Connect: func(ctx context.Context) (*pgx.Conn, error) { + return pgx.Connect(ctx, os.Getenv("discoveryDbUrl")) + }, + LogError: func(ctx context.Context, err error) { + log.Println("Listener error:", err) + }, + // Reconnect after 10s on error + ReconnectDelay: 10 * time.Second, + } + + // generic handler to just print NOTIFY payload + // todo: specific handlers to re-index records + logNotify := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + fmt.Println(notification.Channel, notification.Payload) + return nil + }) + + // Register handler for "my_channel" + listener.Handle("reposts", logNotify) + listener.Handle("saves", logNotify) + listener.Handle("listens", logNotify) + listener.Handle("tracks", logNotify) + listener.Handle("users", logNotify) + listener.Handle("playlists", logNotify) + listener.Handle("follows", logNotify) + listener.Handle("aggregate_track", logNotify) + listener.Handle("aggregate_user", logNotify) + listener.Handle("playlist_track", logNotify) + listener.Handle("aggregate_plays", logNotify) + + fmt.Println("🚀 Starting listener...") + if err := listener.Listen(ctx); err != nil { + log.Fatalf("Listener terminated: %v", err) + } +} From fc40d4170e0d393fdff35bf80998f15cfc559f5b Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Fri, 20 Jun 2025 16:42:39 -0400 Subject: [PATCH 20/30] reorganize code... dedicated users / tracks / playlists search endpoints --- .../searchv1/dsl_helpers.go | 47 ++++- {searcher => api/searchv1}/playlist_search.go | 29 ++- {searcher => api/searchv1}/track_search.go | 6 +- {searcher => api/searchv1}/user_search.go | 7 +- api/server.go | 6 +- api/v1_playlists_search.go | 16 ++ api/v1_search.go | 198 ++++++++++++++++++ api/v1_search_autocomplete.go | 173 --------------- ...autocomplete_test.go => v1_search_test.go} | 4 +- api/v1_tracks_search.go | 16 ++ api/v1_users_search.go | 22 +- {searcher => esindexer}/base_indexer.go | 4 +- {searcher => esindexer}/conn.go | 2 +- {searcher => esindexer}/listen_demo/listen.go | 0 {searcher => esindexer}/playlist_indexer.go | 2 +- {searcher => esindexer}/reindex.go | 17 +- .../dsl_test.go => esindexer/reindex_test.go | 31 +-- {searcher => esindexer}/social_indexer.go | 2 +- {searcher => esindexer}/track_indexer.go | 2 +- {searcher => esindexer}/user_indexer.go | 2 +- go.mod | 4 - go.sum | 13 -- main.go | 4 +- searcher/dsl_helpers.go | 66 ------ searcher/playlist_search_test.go | 16 -- searcher/track_search_test.go | 22 -- searcher/user_search_test.go | 17 -- 27 files changed, 340 insertions(+), 388 deletions(-) rename searcher/search_and_pluck.go => api/searchv1/dsl_helpers.go (53%) rename {searcher => api/searchv1}/playlist_search.go (63%) rename {searcher => api/searchv1}/track_search.go (94%) rename {searcher => api/searchv1}/user_search.go (87%) create mode 100644 api/v1_playlists_search.go create mode 100644 api/v1_search.go delete mode 100644 api/v1_search_autocomplete.go rename api/{v1_search_autocomplete_test.go => v1_search_test.go} (99%) create mode 100644 api/v1_tracks_search.go rename {searcher => esindexer}/base_indexer.go (98%) rename {searcher => esindexer}/conn.go (92%) rename {searcher => esindexer}/listen_demo/listen.go (100%) rename {searcher => esindexer}/playlist_indexer.go (99%) rename {searcher => esindexer}/reindex.go (85%) rename searcher/dsl_test.go => esindexer/reindex_test.go (58%) rename {searcher => esindexer}/social_indexer.go (99%) rename {searcher => esindexer}/track_indexer.go (99%) rename {searcher => esindexer}/user_indexer.go (98%) delete mode 100644 searcher/dsl_helpers.go delete mode 100644 searcher/playlist_search_test.go delete mode 100644 searcher/track_search_test.go delete mode 100644 searcher/user_search_test.go diff --git a/searcher/search_and_pluck.go b/api/searchv1/dsl_helpers.go similarity index 53% rename from searcher/search_and_pluck.go rename to api/searchv1/dsl_helpers.go index 5284345a..0dae1ede 100644 --- a/searcher/search_and_pluck.go +++ b/api/searchv1/dsl_helpers.go @@ -1,7 +1,8 @@ -package searcher +package searchv1 import ( "context" + "encoding/json" "fmt" "io" "strings" @@ -9,8 +10,48 @@ import ( "github.com/elastic/go-elasticsearch/v8" "github.com/elastic/go-elasticsearch/v8/esapi" "github.com/tidwall/gjson" + "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": "sum", + "score_mode": "sum", + "functions": [ + { + "field_value_factor": { + "field": %q, + "factor": 100, + "modifier": "log1p", + "missing": 0 + } + } + ] + } + } + }`, innerJson, scoreField) + + // pprintJson(dsl) + return dsl +} + func SearchAndPluck(esClient *elasticsearch.Client, index, dsl string, limit, offset int) ([]int32, error) { req := esapi.SearchRequest{ Index: []string{index}, @@ -45,3 +86,7 @@ func SearchAndPluck(esClient *elasticsearch.Client, index, dsl string, limit, of return result, nil } + +func pprintJson(j string) { + fmt.Println(string(pretty.Pretty([]byte(j)))) +} diff --git a/searcher/playlist_search.go b/api/searchv1/playlist_search.go similarity index 63% rename from searcher/playlist_search.go rename to api/searchv1/playlist_search.go index c771574b..3c7c3fd0 100644 --- a/searcher/playlist_search.go +++ b/api/searchv1/playlist_search.go @@ -1,4 +1,4 @@ -package searcher +package searchv1 import ( "fmt" @@ -20,15 +20,28 @@ func (q *PlaylistSearchQuery) Map() map[string]any { builder := esquery.Bool() if q.IsTagSearch { - builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tags").Type(esquery.MatchTypeBoolPrefix)) + 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", "user.handle", "user.name").Type(esquery.MatchTypeBoolPrefix)) + builder.Must(esquery.MultiMatch().Query(q.Query).Fields("title", "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", toAnySlice(q.Genres)...)) + } + + if len(q.Moods) > 0 { + builder.Filter(esquery.Terms("tracks.mood", toAnySlice(q.Moods)...)) + } + + if q.OnlyVerified { + builder.Must(esquery.Term("tracks.user.is_verified", true)) + } + + // personalize results if q.MyID > 0 { builder.Should(esquery.CustomQuery(map[string]any{ "terms": map[string]any{ @@ -42,11 +55,9 @@ func (q *PlaylistSearchQuery) Map() map[string]any { })) } - // todo: mood, genre, tags - - if q.OnlyVerified { - builder.Must(esquery.Term("tracks.user.is_verified", true)) - } - return builder.Map() } + +func (q *PlaylistSearchQuery) DSL() string { + return BuildFunctionScoreDSL("repost_count", q.Map()) +} diff --git a/searcher/track_search.go b/api/searchv1/track_search.go similarity index 94% rename from searcher/track_search.go rename to api/searchv1/track_search.go index 97192124..a3b80995 100644 --- a/searcher/track_search.go +++ b/api/searchv1/track_search.go @@ -1,4 +1,4 @@ -package searcher +package searchv1 import ( "fmt" @@ -92,3 +92,7 @@ func (q *TrackSearchQuery) Map() map[string]any { return builder.Map() } + +func (q *TrackSearchQuery) DSL() string { + return BuildFunctionScoreDSL("repost_count", q.Map()) +} diff --git a/searcher/user_search.go b/api/searchv1/user_search.go similarity index 87% rename from searcher/user_search.go rename to api/searchv1/user_search.go index 4fa43d6f..04c3dc87 100644 --- a/searcher/user_search.go +++ b/api/searchv1/user_search.go @@ -1,4 +1,4 @@ -package searcher +package searchv1 import ( "fmt" @@ -43,3 +43,8 @@ func (q *UserSearchQuery) Map() map[string]any { return builder.Map() } + +func (q *UserSearchQuery) DSL() string { + inner := q.Map() + return BuildFunctionScoreDSL("follower_count", inner) +} diff --git a/api/server.go b/api/server.go index 7bd36a4f..67a41dcc 100644 --- a/api/server.go +++ b/api/server.go @@ -14,7 +14,7 @@ import ( "bridgerton.audius.co/api/spl/programs/claimable_tokens" "bridgerton.audius.co/api/spl/programs/reward_manager" "bridgerton.audius.co/config" - "bridgerton.audius.co/searcher" + "bridgerton.audius.co/esindexer" "bridgerton.audius.co/trashid" "github.com/AudiusProject/audiusd/pkg/rewards" "github.com/AudiusProject/audiusd/pkg/sdk" @@ -170,7 +170,7 @@ func NewApiServer(config config.Config) *ApiServer { panic(err) } - esClient, err := searcher.Dial(config.EsUrl) + esClient, err := esindexer.Dial(config.EsUrl) if err != nil { panic(err) } @@ -310,6 +310,7 @@ func NewApiServer(config config.Config) *ApiServer { // Tracks g.Get("/tracks", app.v1Tracks) + g.Get("/tracks/search", app.v1TracksSearch) g.Get("/tracks/unclaimed_id", app.v1TracksUnclaimedId) g.Get("/tracks/trending", app.v1TracksTrending) @@ -331,6 +332,7 @@ func NewApiServer(config config.Config) *ApiServer { // Playlists g.Get("/playlists", app.v1Playlists) + g.Get("/playlists/search", app.v1PlaylistsSearch) g.Get("/playlists/unclaimed_id", app.v1PlaylistsUnclaimedId) g.Get("/playlists/trending", app.v1PlaylistsTrending) g.Get("/playlists/by_permalink/:handle/:slug", app.v1PlaylistByPermalink) diff --git a/api/v1_playlists_search.go b/api/v1_playlists_search.go new file mode 100644 index 00000000..a24338be --- /dev/null +++ b/api/v1_playlists_search.go @@ -0,0 +1,16 @@ +package api + +import ( + "github.com/gofiber/fiber/v2" +) + +func (app *ApiServer) v1PlaylistsSearch(c *fiber.Ctx) error { + playlists, err := app.searchPlaylists(c) + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": playlists, + }) +} diff --git a/api/v1_search.go b/api/v1_search.go new file mode 100644 index 00000000..4d05aa9c --- /dev/null +++ b/api/v1_search.go @@ -0,0 +1,198 @@ +package api + +import ( + "strings" + + "bridgerton.audius.co/api/dbv1" + "bridgerton.audius.co/api/searchv1" + "github.com/gofiber/fiber/v2" + "golang.org/x/sync/errgroup" +) + +func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { + kind := c.Query("kind", "all") + + g := errgroup.Group{} + var users = []dbv1.FullUser{} + var tracks = []dbv1.FullTrack{} + var playlists = []dbv1.FullPlaylist{} + var albums = []dbv1.FullPlaylist{} + + // users + g.Go(func() (err error) { + if kind != "all" && kind != "users" { + return nil + } + + users, err = app.searchUsers(c) + return err + }) + + // tracks + g.Go(func() (err error) { + if kind != "all" && kind != "tracks" { + return nil + } + + tracks, err = app.searchTracks(c) + return err + }) + + // playlists + g.Go(func() (err error) { + if kind != "all" && kind != "playlists" { + return nil + } + + playlists, err = app.searchPlaylists(c) + return err + }) + + // albums + g.Go(func() (err error) { + if kind != "all" && kind != "albums" { + return nil + } + + albums, err = app.searchAlbums(c) + return err + }) + + err := g.Wait() + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": fiber.Map{ + "users": users, + "tracks": tracks, + "playlists": playlists, + "albums": albums, + + // todos + "saved_albums": []any{}, + "saved_users": []any{}, + "saved_tracks": []any{}, + "saved_playlists": []any{}, + }, + }) +} + +func (app *ApiServer) searchUsers(c *fiber.Ctx) ([]dbv1.FullUser, error) { + isTagSearch := strings.Contains(c.Route().Path, "search/tags") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + myId := app.getMyId(c) + + q := searchv1.UserSearchQuery{ + Query: c.Query("query"), + IsVerified: c.QueryBool("is_verified"), + IsTagSearch: isTagSearch, + MyID: myId, + } + + userIds, err := searchv1.SearchAndPluck(app.esClient, "users", q.DSL(), limit, offset) + if err != nil { + return nil, err + } + + users, err := app.queries.FullUsers(c.Context(), dbv1.GetUsersParams{ + Ids: userIds, + MyID: myId, + }) + return users, err +} + +func (app *ApiServer) searchTracks(c *fiber.Ctx) ([]dbv1.FullTrack, error) { + isTagSearch := strings.Contains(c.Route().Path, "search/tags") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + myId := app.getMyId(c) + + q := searchv1.TrackSearchQuery{ + MyID: myId, + IsTagSearch: isTagSearch, + Query: c.Query("query"), + Genres: queryMutli(c, "genre"), + Moods: queryMutli(c, "mood"), + MinBPM: c.QueryInt("bpm_min"), + MaxBPM: c.QueryInt("bpm_max"), + MusicalKeys: queryMutli(c, "key"), + IsDownloadable: c.QueryBool("is_downloadable"), + IsPurchaseable: c.QueryBool("is_purchaseable"), + OnlyVerified: c.QueryBool("only_verified"), + } + + tracksIds, err := searchv1.SearchAndPluck(app.esClient, "tracks", q.DSL(), limit, offset) + if err != nil { + return nil, err + } + + tracks, err := app.queries.FullTracks(c.Context(), dbv1.FullTracksParams{ + GetTracksParams: dbv1.GetTracksParams{ + Ids: tracksIds, + MyID: myId, + }, + }) + return tracks, err +} + +func (app *ApiServer) searchPlaylists(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) { + isTagSearch := strings.Contains(c.Route().Path, "search/tags") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + myId := app.getMyId(c) + + q := searchv1.PlaylistSearchQuery{ + MyID: myId, + IsTagSearch: isTagSearch, + Query: c.Query("query"), + Genres: queryMutli(c, "genre"), + Moods: queryMutli(c, "mood"), + OnlyVerified: c.QueryBool("only_verified"), + } + + playlistsIds, err := searchv1.SearchAndPluck(app.esClient, "playlists", q.DSL(), limit, offset) + if err != nil { + return nil, err + } + + playlists, err := app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ + GetPlaylistsParams: dbv1.GetPlaylistsParams{ + Ids: playlistsIds, + MyID: myId, + }, + }) + return playlists, err +} + +func (app *ApiServer) searchAlbums(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) { + isTagSearch := strings.Contains(c.Route().Path, "search/tags") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + myId := app.getMyId(c) + + q := searchv1.PlaylistSearchQuery{ + MyID: myId, + IsTagSearch: isTagSearch, + Query: c.Query("query"), + Genres: queryMutli(c, "genre"), + Moods: queryMutli(c, "mood"), + OnlyVerified: c.QueryBool("only_verified"), + IsAlbum: true, + } + + playlistsIds, err := searchv1.SearchAndPluck(app.esClient, "playlists", q.DSL(), limit, offset) + if err != nil { + return nil, err + } + + playlists, err := app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ + GetPlaylistsParams: dbv1.GetPlaylistsParams{ + Ids: playlistsIds, + MyID: myId, + }, + }) + return playlists, err +} diff --git a/api/v1_search_autocomplete.go b/api/v1_search_autocomplete.go deleted file mode 100644 index dc8c5219..00000000 --- a/api/v1_search_autocomplete.go +++ /dev/null @@ -1,173 +0,0 @@ -package api - -import ( - "strings" - - "bridgerton.audius.co/api/dbv1" - "bridgerton.audius.co/searcher" - "github.com/gofiber/fiber/v2" - "golang.org/x/sync/errgroup" -) - -func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { - - isTagSearch := strings.Contains(c.Route().Path, "search/tags") - - kind := c.Query("kind", "all") - query := c.Query("query") - genres := queryMutli(c, "genre") - moods := queryMutli(c, "mood") - limit := c.QueryInt("limit", 10) - offset := c.QueryInt("offset", 0) - - myId := app.getMyId(c) - - g := errgroup.Group{} - var users = []dbv1.FullUser{} - var tracks = []dbv1.FullTrack{} - var playlists = []dbv1.FullPlaylist{} - var albums = []dbv1.FullPlaylist{} - - // users - g.Go(func() error { - if kind != "all" && kind != "users" { - return nil - } - - q := searcher.UserSearchQuery{ - Query: query, - IsVerified: c.QueryBool("is_verified"), - IsTagSearch: isTagSearch, - MyID: myId, - } - - dsl := searcher.BuildFunctionScoreDSL("follower_count", q.Map()) - userIds, err := searcher.SearchAndPluck(app.esClient, "users", dsl, limit, offset) - if err != nil { - return err - } - - users, err = app.queries.FullUsers(c.Context(), dbv1.GetUsersParams{ - Ids: userIds, - MyID: myId, - }) - return err - }) - - // tracks - g.Go(func() error { - if kind != "all" && kind != "tracks" { - return nil - } - - q := searcher.TrackSearchQuery{ - Query: query, - Genres: genres, - Moods: moods, - MinBPM: c.QueryInt("bpm_min"), - MaxBPM: c.QueryInt("bpm_max"), - MusicalKeys: queryMutli(c, "key"), - IsDownloadable: c.QueryBool("is_downloadable"), - IsPurchaseable: c.QueryBool("is_purchaseable"), - OnlyVerified: c.QueryBool("only_verified"), - - // todo: includePurchaseable - - IsTagSearch: isTagSearch, - MyID: myId, - } - - dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) - - tracksIds, err := searcher.SearchAndPluck(app.esClient, "tracks", dsl, limit, offset) - if err != nil { - return err - } - - tracks, err = app.queries.FullTracks(c.Context(), dbv1.FullTracksParams{ - GetTracksParams: dbv1.GetTracksParams{ - Ids: tracksIds, - MyID: myId, - }, - }) - return err - }) - - // playlists - g.Go(func() error { - if kind != "all" && kind != "playlists" { - return nil - } - - q := searcher.PlaylistSearchQuery{ - Query: query, - MyID: myId, - OnlyVerified: c.QueryBool("only_verified"), - IsTagSearch: isTagSearch, - } - - dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) - - playlistsIds, err := searcher.SearchAndPluck(app.esClient, "playlists", dsl, limit, offset) - if err != nil { - return err - } - - playlists, err = app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ - GetPlaylistsParams: dbv1.GetPlaylistsParams{ - Ids: playlistsIds, - MyID: myId, - - // todo: playlist needs to support modds + genres + tags query - }, - }) - return err - }) - - // albums - g.Go(func() error { - if kind != "all" && kind != "albums" { - return nil - } - - q := searcher.PlaylistSearchQuery{ - Query: query, - IsAlbum: true, - } - - dsl := searcher.BuildFunctionScoreDSL("repost_count", q.Map()) - - playlistsIds, err := searcher.SearchAndPluck(app.esClient, "playlists", dsl, limit, offset) - if err != nil { - return err - } - - albums, err = app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ - GetPlaylistsParams: dbv1.GetPlaylistsParams{ - Ids: playlistsIds, - MyID: myId, - }, - }) - return err - }) - - err := g.Wait() - if err != nil { - return err - } - - return c.JSON(fiber.Map{ - "data": fiber.Map{ - "users": users, - "tracks": tracks, - "playlists": playlists, - "albums": albums, - - // todos - "saved_albums": []any{}, - "saved_users": []any{}, - "saved_tracks": []any{}, - "saved_playlists": []any{}, - }, - }) -} diff --git a/api/v1_search_autocomplete_test.go b/api/v1_search_test.go similarity index 99% rename from api/v1_search_autocomplete_test.go rename to api/v1_search_test.go index ab014b54..fe34304f 100644 --- a/api/v1_search_autocomplete_test.go +++ b/api/v1_search_test.go @@ -3,7 +3,7 @@ package api import ( "testing" - "bridgerton.audius.co/searcher" + "bridgerton.audius.co/esindexer" "github.com/test-go/testify/require" ) @@ -135,7 +135,7 @@ func TestSearch(t *testing.T) { createFixtures(app, fixtures) // index data to ES - searcher.Reindex(app.pool, app.esClient, true) + esindexer.Reindex(app.pool, app.esClient, true) // users: { diff --git a/api/v1_tracks_search.go b/api/v1_tracks_search.go new file mode 100644 index 00000000..48b0daae --- /dev/null +++ b/api/v1_tracks_search.go @@ -0,0 +1,16 @@ +package api + +import ( + "github.com/gofiber/fiber/v2" +) + +func (app *ApiServer) v1TracksSearch(c *fiber.Ctx) error { + tracks, err := app.searchTracks(c) + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": tracks, + }) +} diff --git a/api/v1_users_search.go b/api/v1_users_search.go index f61cc4a1..428bedd9 100644 --- a/api/v1_users_search.go +++ b/api/v1_users_search.go @@ -1,31 +1,11 @@ package api import ( - "bridgerton.audius.co/api/dbv1" - "bridgerton.audius.co/searcher" "github.com/gofiber/fiber/v2" ) func (app *ApiServer) v1UsersSearch(c *fiber.Ctx) error { - myId := app.getMyId(c) - limit := c.QueryInt("limit", 10) - offset := c.QueryInt("offset", 0) - - q := searcher.UserSearchQuery{ - Query: c.Query("query"), - IsVerified: c.QueryBool("is_verified"), - } - - dsl := searcher.BuildFunctionScoreDSL("follower_count", q.Map()) - userIds, err := searcher.SearchAndPluck(app.esClient, "users", dsl, limit, offset) - if err != nil { - return err - } - - users, err := app.queries.FullUsers(c.Context(), dbv1.GetUsersParams{ - Ids: userIds, - MyID: myId, - }) + users, err := app.searchUsers(c) if err != nil { return err } diff --git a/searcher/base_indexer.go b/esindexer/base_indexer.go similarity index 98% rename from searcher/base_indexer.go rename to esindexer/base_indexer.go index b0e78194..f1c6e9b7 100644 --- a/searcher/base_indexer.go +++ b/esindexer/base_indexer.go @@ -1,4 +1,4 @@ -package searcher +package esindexer import ( "context" @@ -72,7 +72,7 @@ func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { body, _ := io.ReadAll(res.Body) maxBlocknumber = gjson.GetBytes(body, "aggregations.max_blocknumber.value").Int() - pprintJson(string(body)) + // pprintJson(string(body)) fmt.Println("________ maxBlocknumber", maxBlocknumber) } diff --git a/searcher/conn.go b/esindexer/conn.go similarity index 92% rename from searcher/conn.go rename to esindexer/conn.go index 68b3237b..e43bd98c 100644 --- a/searcher/conn.go +++ b/esindexer/conn.go @@ -1,4 +1,4 @@ -package searcher +package esindexer import "github.com/elastic/go-elasticsearch/v8" diff --git a/searcher/listen_demo/listen.go b/esindexer/listen_demo/listen.go similarity index 100% rename from searcher/listen_demo/listen.go rename to esindexer/listen_demo/listen.go diff --git a/searcher/playlist_indexer.go b/esindexer/playlist_indexer.go similarity index 99% rename from searcher/playlist_indexer.go rename to esindexer/playlist_indexer.go index 173b4919..b8e790e0 100644 --- a/searcher/playlist_indexer.go +++ b/esindexer/playlist_indexer.go @@ -1,4 +1,4 @@ -package searcher +package esindexer type PlaylistIndexer struct { *BaseIndexer diff --git a/searcher/reindex.go b/esindexer/reindex.go similarity index 85% rename from searcher/reindex.go rename to esindexer/reindex.go index b23d0ac5..8da8bacf 100644 --- a/searcher/reindex.go +++ b/esindexer/reindex.go @@ -1,4 +1,4 @@ -package searcher +package esindexer import ( "context" @@ -8,6 +8,7 @@ import ( "bridgerton.audius.co/config" "github.com/elastic/go-elasticsearch/v8" "github.com/jackc/pgx/v5/pgxpool" + "github.com/tidwall/sjson" ) func mustDialPostgres() *pgxpool.Pool { @@ -31,6 +32,20 @@ func mustDialElasticsearch() *elasticsearch.Client { return esc } +func commonIndexSettings(mapping string) string { + mustSet := func(key string, value any) { + var err error + mapping, err = sjson.Set(mapping, key, value) + if err != nil { + panic(err) + } + } + + mustSet("settings.number_of_shards", 1) + mustSet("settings.number_of_replicas", 0) + return mapping +} + func reindexPlaylists(base *BaseIndexer) { i := &PlaylistIndexer{base} diff --git a/searcher/dsl_test.go b/esindexer/reindex_test.go similarity index 58% rename from searcher/dsl_test.go rename to esindexer/reindex_test.go index f0e54ee1..bf457f43 100644 --- a/searcher/dsl_test.go +++ b/esindexer/reindex_test.go @@ -1,40 +1,11 @@ -package searcher +package esindexer import ( - "context" - "strings" "testing" "bridgerton.audius.co/utils" - "github.com/elastic/go-elasticsearch/v8/esapi" - "github.com/stretchr/testify/require" ) -func testSearch(t *testing.T, indexName, dsl string) { - t.Helper() - - pprintJson(dsl) - - esClient, err := Dial("http://localhost:21400") - require.NoError(t, err) - - req := esapi.SearchRequest{ - Index: []string{indexName}, - Body: strings.NewReader(dsl), - } - - res, err := req.Do(context.Background(), esClient) - require.NoError(t, err) - body := res.String() - - if res.IsError() { - require.FailNow(t, body) - } - - pprintJson(body) - // todo: assert not empty and stuff... -} - func TestCommonIndexSettings(t *testing.T) { { mapping := `{ diff --git a/searcher/social_indexer.go b/esindexer/social_indexer.go similarity index 99% rename from searcher/social_indexer.go rename to esindexer/social_indexer.go index 41673914..e26a07c3 100644 --- a/searcher/social_indexer.go +++ b/esindexer/social_indexer.go @@ -1,4 +1,4 @@ -package searcher +package esindexer // user id => list of following, repost (tracks), save (tracks), repost (playlists), repost (playlist) type SocialIndexer struct { diff --git a/searcher/track_indexer.go b/esindexer/track_indexer.go similarity index 99% rename from searcher/track_indexer.go rename to esindexer/track_indexer.go index 7f51a91e..e7cf71e0 100644 --- a/searcher/track_indexer.go +++ b/esindexer/track_indexer.go @@ -1,4 +1,4 @@ -package searcher +package esindexer type TrackIndexer struct { *BaseIndexer diff --git a/searcher/user_indexer.go b/esindexer/user_indexer.go similarity index 98% rename from searcher/user_indexer.go rename to esindexer/user_indexer.go index 554a3238..3e9e5f89 100644 --- a/searcher/user_indexer.go +++ b/esindexer/user_indexer.go @@ -1,4 +1,4 @@ -package searcher +package esindexer /* diff --git a/go.mod b/go.mod index ee284643..5d6c0e2a 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,6 @@ require ( github.com/go-playground/validator/v10 v10.26.0 github.com/gofiber/contrib/fiberzap/v2 v2.1.5 github.com/gofiber/fiber/v2 v2.52.6 - github.com/jackc/pgconn v1.14.3 github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f github.com/jackc/pgx/v5 v5.7.4 github.com/jackc/pgxlisten v0.0.0-20241106001234-1d6f6656415c @@ -106,10 +105,7 @@ require ( github.com/gorilla/websocket v1.5.3 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect github.com/holiman/uint256 v1.3.2 // indirect - github.com/jackc/chunkreader/v2 v2.0.1 // indirect - github.com/jackc/pgio v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgproto3/v2 v2.3.3 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jmhodges/levigo v1.0.0 // indirect diff --git a/go.sum b/go.sum index 40fb42b7..8d25dbea 100644 --- a/go.sum +++ b/go.sum @@ -227,19 +227,8 @@ github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyf github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA= github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= -github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/pgconn v1.14.3 h1:bVoTr12EGANZz66nZPkMInAV/KHD2TxH9npjXXgiB3w= -github.com/jackc/pgconn v1.14.3/go.mod h1:RZbme4uasqzybK2RK5c65VsHxoyaml09lx3tXOcO/VM= -github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= -github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUOag= -github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f h1:ahoGnXfh4wiCisojvzq1PzgxzFwJEUHMI26pUY6oluk= @@ -381,7 +370,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -589,7 +577,6 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/main.go b/main.go index ee26beca..46ade413 100644 --- a/main.go +++ b/main.go @@ -7,7 +7,7 @@ import ( "bridgerton.audius.co/api" "bridgerton.audius.co/config" - "bridgerton.audius.co/searcher" + "bridgerton.audius.co/esindexer" ) func main() { @@ -17,7 +17,7 @@ func main() { drop := slices.Contains(collections, "drop") fmt.Println("reindex", "drop", drop, "collections", collections) - searcher.ReindexLegacy(drop, collections...) + esindexer.ReindexLegacy(drop, collections...) return } diff --git a/searcher/dsl_helpers.go b/searcher/dsl_helpers.go deleted file mode 100644 index 2c8edd8c..00000000 --- a/searcher/dsl_helpers.go +++ /dev/null @@ -1,66 +0,0 @@ -package searcher - -import ( - "encoding/json" - "fmt" - - "github.com/tidwall/pretty" - "github.com/tidwall/sjson" -) - -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": "sum", - "score_mode": "sum", - "functions": [ - { - "field_value_factor": { - "field": %q, - "factor": 100, - "modifier": "log1p", - "missing": 0 - } - } - ] - } - } - }`, innerJson, scoreField) - - // pprintJson(dsl) - return dsl -} - -func pprintJson(j string) { - fmt.Println(string(pretty.Pretty([]byte(j)))) -} - -func commonIndexSettings(mapping string) string { - mustSet := func(key string, value any) { - var err error - mapping, err = sjson.Set(mapping, key, value) - if err != nil { - panic(err) - } - } - - mustSet("settings.number_of_shards", 1) - mustSet("settings.number_of_replicas", 0) - return mapping -} diff --git a/searcher/playlist_search_test.go b/searcher/playlist_search_test.go deleted file mode 100644 index b0709d98..00000000 --- a/searcher/playlist_search_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package searcher - -import ( - "testing" -) - -func TestPlaylistDsl(t *testing.T) { - t.Skip() - q := &PlaylistSearchQuery{ - Query: "hot", - MyID: 1, - } - - dsl := BuildFunctionScoreDSL("repost_count", q.Map()) - testSearch(t, "playlists", dsl) -} diff --git a/searcher/track_search_test.go b/searcher/track_search_test.go deleted file mode 100644 index 630df838..00000000 --- a/searcher/track_search_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package searcher - -import ( - "testing" -) - -func TestTrackDsl(t *testing.T) { - t.Skip() - - ts := TrackSearchQuery{ - Query: "KING", - MinBPM: 80, - MaxBPM: 220, - Genres: []string{"Rap"}, - MusicalKeys: []string{"A minor", "B minor"}, - MyID: 1, - } - - dsl := BuildFunctionScoreDSL("repost_count", ts.Map()) - testSearch(t, "tracks", dsl) - -} diff --git a/searcher/user_search_test.go b/searcher/user_search_test.go deleted file mode 100644 index 96272849..00000000 --- a/searcher/user_search_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package searcher - -import ( - "testing" -) - -func TestUserDsl(t *testing.T) { - t.Skip() - q := &UserSearchQuery{ - Query: "ray", - MyID: 1, - } - - dsl := BuildFunctionScoreDSL("followers_count", q.Map()) - - testSearch(t, "users", dsl) -} From abb15351500043239eab9e67703d17e22d0056c9 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Sat, 21 Jun 2025 00:03:36 -0400 Subject: [PATCH 21/30] single indexer with collectionConfigs. Rather than do some subclass style nonsense, just have a single indexer instance, and index configs are just data structs that the single indexer can use. This will make it easier for that indexer to have a listener and respond appropriately. --- Makefile | 5 ++ api/searchv1/playlist_search.go | 2 + api/searchv1/track_search.go | 2 + api/searchv1/user_search.go | 2 + esindexer/{base_indexer.go => indexer.go} | 67 ++++++---------- esindexer/listen_demo/listen.go | 72 +++++++++++++---- esindexer/playlist_indexer.go | 80 ------------------- esindexer/playlists_index.go | 59 ++++++++++++++ esindexer/reindex.go | 52 +++--------- .../{reindex_test.go => settings_test.go} | 0 .../{social_indexer.go => socials_index.go} | 28 +++---- esindexer/track_indexer.go | 66 --------------- esindexer/tracks_index.go | 55 +++++++++++++ esindexer/user_indexer.go | 72 ----------------- esindexer/users_index.go | 48 +++++++++++ 15 files changed, 273 insertions(+), 337 deletions(-) rename esindexer/{base_indexer.go => indexer.go} (64%) delete mode 100644 esindexer/playlist_indexer.go create mode 100644 esindexer/playlists_index.go rename esindexer/{reindex_test.go => settings_test.go} (100%) rename esindexer/{social_indexer.go => socials_index.go} (81%) delete mode 100644 esindexer/track_indexer.go create mode 100644 esindexer/tracks_index.go delete mode 100644 esindexer/user_indexer.go create mode 100644 esindexer/users_index.go diff --git a/Makefile b/Makefile index 95d25ea2..31c78716 100644 --- a/Makefile +++ b/Makefile @@ -20,6 +20,11 @@ production:: ssh prod-discovery-4 -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge' curl 'https://bridgerton.audius.co' +esindexer:: + mkdir -p build/production + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/production/bridge-amd64 + rsync -ravz build/production/ prod-elasticsearch:esindexer + psql:: docker compose exec db psql -U postgres diff --git a/api/searchv1/playlist_search.go b/api/searchv1/playlist_search.go index 3c7c3fd0..963bcb6d 100644 --- a/api/searchv1/playlist_search.go +++ b/api/searchv1/playlist_search.go @@ -39,6 +39,8 @@ func (q *PlaylistSearchQuery) Map() map[string]any { if q.OnlyVerified { builder.Must(esquery.Term("tracks.user.is_verified", true)) + } else { + builder.Should(esquery.Term("user.is_verified", true)) } // personalize results diff --git a/api/searchv1/track_search.go b/api/searchv1/track_search.go index a3b80995..7965fe82 100644 --- a/api/searchv1/track_search.go +++ b/api/searchv1/track_search.go @@ -74,6 +74,8 @@ func (q *TrackSearchQuery) Map() map[string]any { 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 diff --git a/api/searchv1/user_search.go b/api/searchv1/user_search.go index 04c3dc87..8a6a35e3 100644 --- a/api/searchv1/user_search.go +++ b/api/searchv1/user_search.go @@ -39,6 +39,8 @@ func (q *UserSearchQuery) Map() map[string]any { if q.IsVerified { builder.Must(esquery.Term("is_verified", true)) + } else { + builder.Should(esquery.Term("is_verified", true)) } return builder.Map() diff --git a/esindexer/base_indexer.go b/esindexer/indexer.go similarity index 64% rename from esindexer/base_indexer.go rename to esindexer/indexer.go index f1c6e9b7..79940ec4 100644 --- a/esindexer/base_indexer.go +++ b/esindexer/indexer.go @@ -3,23 +3,36 @@ package esindexer import ( "context" "fmt" - "io" "log" "strings" "github.com/elastic/go-elasticsearch/v8" "github.com/elastic/go-elasticsearch/v8/esutil" "github.com/jackc/pgx/v5/pgxpool" - "github.com/tidwall/gjson" ) -type BaseIndexer struct { +type collectionConfig struct { + indexName string + idColumn string + mapping string + sql string +} + +var collectionConfigs = map[string]collectionConfig{ + "users": userConfig, + "tracks": tracksConfig, + "playlists": playlistsConfig, + "socials": socialsConfig, +} + +type EsIndexer struct { pool *pgxpool.Pool esc *elasticsearch.Client + // bulk esutil.BulkIndexer drop bool } -func (base *BaseIndexer) createIndex(indexName string, mapping string) error { +func (base *EsIndexer) createIndex(indexName string) error { if base.drop { _, err := base.esc.Indices.Delete([]string{indexName}) if err != nil { @@ -27,10 +40,12 @@ func (base *BaseIndexer) createIndex(indexName string, mapping string) error { } } + cc := collectionConfigs[indexName] + res, err := base.esc.Indices.Create( indexName, base.esc.Indices.Create.WithBody( - strings.NewReader(mapping), + strings.NewReader(cc.mapping), ), ) if err != nil { @@ -42,44 +57,11 @@ func (base *BaseIndexer) createIndex(indexName string, mapping string) error { return res.Body.Close() } -func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { - - // Get the max updated_at from the Elasticsearch index - var maxBlocknumber int64 - - if false { - - res, err := base.esc.Search( - base.esc.Search.WithIndex(index), - base.esc.Search.WithBody(strings.NewReader(`{ - "size": 0, - "aggs": { - "max_blocknumber": { - "max": { - "field": "blocknumber" - } - } - } - }`)), - base.esc.Search.WithTrackTotalHits(false), - ) - if err != nil { - fmt.Println("error querying max_blocknumber:", err) - return err - } - defer res.Body.Close() - - body, _ := io.ReadAll(res.Body) - maxBlocknumber = gjson.GetBytes(body, "aggregations.max_blocknumber.value").Int() - - // pprintJson(string(body)) - fmt.Println("________ maxBlocknumber", maxBlocknumber) - - } +func (base *EsIndexer) indexAll(indexName string) error { + cc := collectionConfigs[indexName] ctx := context.Background() bulk, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{ - Index: index, Client: base.esc, NumWorkers: 2, Refresh: "true", @@ -88,7 +70,7 @@ func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { log.Fatalf("Error creating the indexer: %s", err) } - rows, err := base.pool.Query(ctx, sql, maxBlocknumber) + rows, err := base.pool.Query(ctx, cc.sql) if err != nil { return err } @@ -104,6 +86,7 @@ func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { err = bulk.Add(ctx, esutil.BulkIndexerItem{ Action: "index", + Index: indexName, DocumentID: fmt.Sprintf("%d", id), Body: strings.NewReader(doc), OnSuccess: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem) { @@ -132,7 +115,7 @@ func (base *BaseIndexer) bulkIndexQuery(index, sql string) error { log.Fatalf("Unexpected error: %s", err) } - fmt.Printf("stats: %s %+v \n", index, bulk.Stats()) + fmt.Printf("stats: %s %+v \n", indexName, bulk.Stats()) return nil } diff --git a/esindexer/listen_demo/listen.go b/esindexer/listen_demo/listen.go index 14b3baa1..eae4bec3 100644 --- a/esindexer/listen_demo/listen.go +++ b/esindexer/listen_demo/listen.go @@ -10,6 +10,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgxlisten" + "github.com/tidwall/gjson" _ "github.com/joho/godotenv/autoload" ) @@ -30,24 +31,65 @@ func main() { } // generic handler to just print NOTIFY payload - // todo: specific handlers to re-index records - logNotify := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { - fmt.Println(notification.Channel, notification.Payload) + // logNotify := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + // fmt.Println(notification.Channel, notification.Payload) + // return nil + // }) + + userHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + id := gjson.Get(notification.Payload, "user_id").Int() + fmt.Println("reindex user:", notification.Channel, id) + // userIndexer.reindexId(id) + return nil + }) + + trackHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + id := gjson.Get(notification.Payload, "track_id").Int() + fmt.Println("reindex track:", notification.Channel, id) return nil }) - // Register handler for "my_channel" - listener.Handle("reposts", logNotify) - listener.Handle("saves", logNotify) - listener.Handle("listens", logNotify) - listener.Handle("tracks", logNotify) - listener.Handle("users", logNotify) - listener.Handle("playlists", logNotify) - listener.Handle("follows", logNotify) - listener.Handle("aggregate_track", logNotify) - listener.Handle("aggregate_user", logNotify) - listener.Handle("playlist_track", logNotify) - listener.Handle("aggregate_plays", logNotify) + playlistHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + id := gjson.Get(notification.Payload, "playlist_id").Int() + fmt.Println("reindex track:", notification.Channel, id) + return nil + }) + + listener.Handle("users", userHandler) + listener.Handle("aggregate_user", userHandler) + listener.Handle("tracks", trackHandler) + listener.Handle("aggregate_track", trackHandler) + listener.Handle("playlists", playlistHandler) + listener.Handle("playlist_track", playlistHandler) + + listener.Handle("follows", pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + followerId := gjson.Get(notification.Payload, "follower_user_id").Int() + followeeId := gjson.Get(notification.Payload, "followee_user_id").Int() + fmt.Println("reindex socials:", followerId, "add follow", followeeId) + return nil + })) + + listener.Handle("reposts", pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + userId := gjson.Get(notification.Payload, "user_id").Int() + isTrack := gjson.Get(notification.Payload, "repost_type").String() == "track" + id := gjson.Get(notification.Payload, "repost_item_id").Int() + fmt.Println("reindex socials:", userId, "add repost", isTrack, id) + return nil + })) + + listener.Handle("saves", pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + userId := gjson.Get(notification.Payload, "user_id").Int() + isTrack := gjson.Get(notification.Payload, "save_type").String() == "track" + id := gjson.Get(notification.Payload, "save_item_id").Int() + fmt.Println("reindex socials:", userId, "add save", isTrack, id) + return nil + })) + + // listener.Handle("reposts", logNotify) + // listener.Handle("saves", logNotify) + + // listener.Handle("listens", logNotify) + // listener.Handle("aggregate_plays", logNotify) fmt.Println("🚀 Starting listener...") if err := listener.Listen(ctx); err != nil { diff --git a/esindexer/playlist_indexer.go b/esindexer/playlist_indexer.go deleted file mode 100644 index b8e790e0..00000000 --- a/esindexer/playlist_indexer.go +++ /dev/null @@ -1,80 +0,0 @@ -package esindexer - -type PlaylistIndexer struct { - *BaseIndexer -} - -func (pi *PlaylistIndexer) createIndex() error { - // Specify mappings for playlist index - // Only specifying properties that might be ambiguous - mapping := `{ - "mappings": { - "properties": { - } - } - }` - return pi.BaseIndexer.createIndex("playlists", mapping) -} - -func (pi *PlaylistIndexer) indexAll() error { - // todo: track stubs - sql := ` - SELECT - playlist_id, - json_build_object( - 'title', playlist_name, - 'description', description, - 'track_count', track_count, - 'save_count', aggregate_playlist.save_count, - 'repost_count', aggregate_playlist.repost_count, - 'created_at', playlists.created_at, - 'updated_at', playlists.updated_at, - 'blocknumber', playlists.blocknumber, - 'is_private', is_private, - 'is_album', playlists.is_album, - 'user', json_build_object( - 'handle', users.handle, - 'name', users.name, - 'location', users.location, - 'follower_count', aggregate_user.follower_count, - 'is_verified', is_verified - ), - 'tracks', ( - SELECT json_agg( - json_build_object( - 'title', title, - 'genre', genre, - 'mood', mood, - 'tags', string_to_array(tags, ','), - - -- todo: more track fields - 'user', json_build_object( - 'handle', users.handle, - 'name', users.name, - 'location', users.location, - 'follower_count', aggregate_user.follower_count, - 'is_verified', is_verified - ) - ) - ) - FROM playlist_tracks - JOIN tracks USING (track_id) - JOIN users ON owner_id = user_id - WHERE playlist_id = playlists.playlist_id - ) - ) - FROM playlists - JOIN aggregate_playlist USING (playlist_id) - JOIN users ON playlist_owner_id = user_id - JOIN aggregate_user USING (user_id) - WHERE is_private = false - AND users.is_available = true - AND users.is_deactivated = false - AND playlists.blocknumber > $1 - ORDER BY playlists.blocknumber ASC - - -- LIMIT 1000 - ` - - return pi.bulkIndexQuery("playlists", sql) -} diff --git a/esindexer/playlists_index.go b/esindexer/playlists_index.go new file mode 100644 index 00000000..4829b213 --- /dev/null +++ b/esindexer/playlists_index.go @@ -0,0 +1,59 @@ +package esindexer + +var playlistsConfig = collectionConfig{ + indexName: "playlists", + idColumn: "playlist_id", + sql: ` + SELECT + playlist_id, + json_build_object( + 'title', playlist_name, + 'description', description, + 'track_count', track_count, + 'save_count', aggregate_playlist.save_count, + 'repost_count', aggregate_playlist.repost_count, + 'created_at', playlists.created_at, + 'updated_at', playlists.updated_at, + 'blocknumber', playlists.blocknumber, + 'is_private', is_private, + 'is_album', playlists.is_album, + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified + ), + 'tracks', ( + SELECT json_agg( + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'tags', string_to_array(tags, ','), + + -- todo: more track fields + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified + ) + ) + ) + FROM playlist_tracks + JOIN tracks USING (track_id) + JOIN users ON owner_id = user_id + WHERE playlist_id = playlists.playlist_id + ) + ) + FROM playlists + JOIN aggregate_playlist USING (playlist_id) + JOIN users ON playlist_owner_id = user_id + JOIN aggregate_user USING (user_id) + WHERE is_private = false + AND users.is_available = true + AND users.is_deactivated = false + `, +} diff --git a/esindexer/reindex.go b/esindexer/reindex.go index 8da8bacf..9cc9787b 100644 --- a/esindexer/reindex.go +++ b/esindexer/reindex.go @@ -46,71 +46,37 @@ func commonIndexSettings(mapping string) string { return mapping } -func reindexPlaylists(base *BaseIndexer) { - i := &PlaylistIndexer{base} +func reindexCollection(i *EsIndexer, collection string) { - if err := i.createIndex(); err != nil { + if err := i.createIndex(collection); err != nil { panic(err) } - if err := i.indexAll(); err != nil { - panic(err) - } -} - -func reindexUsers(base *BaseIndexer) { - i := &UserIndexer{base} - - if err := i.createIndex(); err != nil { - panic(err) - } - if err := i.indexAll(); err != nil { - panic(err) - } -} - -func reindexTracks(base *BaseIndexer) { - i := &TrackIndexer{base} - - if err := i.createIndex(); err != nil { - panic(err) - } - if err := i.indexAll(); err != nil { - panic(err) - } -} - -func reindexSocials(base *BaseIndexer) { - i := &SocialIndexer{base} - - if err := i.createIndex(); err != nil { - panic(err) - } - if err := i.indexAll(); err != nil { + if err := i.indexAll(collection); err != nil { panic(err) } } func Reindex(pool *pgxpool.Pool, esc *elasticsearch.Client, drop bool, collections ...string) { - baseIndexer := &BaseIndexer{ + baseIndexer := &EsIndexer{ pool, esc, drop, } - reindexAll := len(collections) == 0 + reindexAll := len(collections) == 0 || slices.Contains(collections, "all") if reindexAll || slices.Contains(collections, "playlists") { - reindexPlaylists(baseIndexer) + reindexCollection(baseIndexer, "playlists") } if reindexAll || slices.Contains(collections, "tracks") { - reindexTracks(baseIndexer) + reindexCollection(baseIndexer, "tracks") } if reindexAll || slices.Contains(collections, "users") { - reindexUsers(baseIndexer) + reindexCollection(baseIndexer, "users") } if reindexAll || slices.Contains(collections, "socials") { - reindexSocials(baseIndexer) + reindexCollection(baseIndexer, "socials") } } diff --git a/esindexer/reindex_test.go b/esindexer/settings_test.go similarity index 100% rename from esindexer/reindex_test.go rename to esindexer/settings_test.go diff --git a/esindexer/social_indexer.go b/esindexer/socials_index.go similarity index 81% rename from esindexer/social_indexer.go rename to esindexer/socials_index.go index e26a07c3..e4100983 100644 --- a/esindexer/social_indexer.go +++ b/esindexer/socials_index.go @@ -1,12 +1,12 @@ package esindexer // user id => list of following, repost (tracks), save (tracks), repost (playlists), repost (playlist) -type SocialIndexer struct { - *BaseIndexer -} -func (ui *SocialIndexer) createIndex() error { - mapping := `{ +var socialsConfig = collectionConfig{ + indexName: "socials", + idColumn: "user_id", + mapping: ` + { "mappings": { "properties": { "saved_track_ids": { "type": "keyword" }, @@ -16,12 +16,8 @@ func (ui *SocialIndexer) createIndex() error { "following_user_ids": { "type": "keyword" } } } - }` - return ui.BaseIndexer.createIndex("socials", mapping) -} - -func (ui *SocialIndexer) indexAll() error { - sql := ` + }`, + sql: ` select user_id, json_build_object ( @@ -84,13 +80,7 @@ func (ui *SocialIndexer) indexAll() error { from aggregate_user users - -- normally blocknumber ($1) would be used as indexing cursor - -- but atm there's no way to do the social index incrementally - -- so do this to use the $1 parameter - WHERE -1 < $1 - + -- todo remove LIMIT 1000 - ` - - return ui.bulkIndexQuery("socials", sql) + `, } diff --git a/esindexer/track_indexer.go b/esindexer/track_indexer.go deleted file mode 100644 index e7cf71e0..00000000 --- a/esindexer/track_indexer.go +++ /dev/null @@ -1,66 +0,0 @@ -package esindexer - -type TrackIndexer struct { - *BaseIndexer -} - -func (ti *TrackIndexer) createIndex() error { - // we rely on elasticsearch dynamic mapping - // so we only need to specify properties that might be ambigious (int vs float) - mapping := `{ - "mappings": { - "properties": { - "bpm": { "type": "float" } - } - } - }` - return ti.BaseIndexer.createIndex("tracks", mapping) -} - -func (ti *TrackIndexer) indexAll() error { - sql := ` - SELECT - track_id, - json_build_object( - 'title', title, - 'genre', genre, - 'mood', mood, - 'duration', duration, - 'save_count', aggregate_track.save_count, - 'repost_count', aggregate_track.repost_count, - 'comment_count', aggregate_track.comment_count, - 'release_date', coalesce(release_date, tracks.created_at), - 'updated_at', tracks.updated_at, - 'blocknumber', tracks.blocknumber, - 'musical_key', musical_key, - 'bpm', bpm, - 'tags', string_to_array(tags, ','), - 'is_downloadable', is_downloadable, - 'has_stems', (select true from stems where parent_track_id = tracks.track_id limit 1), - 'download_conditions', download_conditions, - 'stream_conditions', stream_conditions, - 'user', json_build_object( - 'handle', users.handle, - 'name', users.name, - 'location', users.location, - 'follower_count', aggregate_user.follower_count, - 'is_verified', is_verified - ) - ) - FROM tracks - JOIN aggregate_track USING (track_id) - JOIN users ON owner_id = user_id - JOIN aggregate_user USING (user_id) - WHERE tracks.is_unlisted = false - AND tracks.is_delete = false - AND tracks.is_available = true - AND users.is_available = true - AND users.is_deactivated = false - AND tracks.blocknumber > $1 - ORDER BY tracks.blocknumber ASC - - -- LIMIT 1000 - ` - - return ti.bulkIndexQuery("tracks", sql) -} diff --git a/esindexer/tracks_index.go b/esindexer/tracks_index.go new file mode 100644 index 00000000..94d6ae49 --- /dev/null +++ b/esindexer/tracks_index.go @@ -0,0 +1,55 @@ +package esindexer + +var tracksConfig = collectionConfig{ + // indexName: , + idColumn: "track_id", + mapping: ` + { + "mappings": { + "properties": { + "bpm": { "type": "float" } + } + } + }`, + sql: ` + SELECT + track_id, + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'duration', duration, + 'save_count', aggregate_track.save_count, + 'repost_count', aggregate_track.repost_count, + 'comment_count', aggregate_track.comment_count, + 'release_date', coalesce(release_date, tracks.created_at), + 'updated_at', tracks.updated_at, + 'blocknumber', tracks.blocknumber, + 'musical_key', musical_key, + 'bpm', bpm, + 'tags', string_to_array(tags, ','), + 'is_downloadable', is_downloadable, + 'has_stems', (select true from stems where parent_track_id = tracks.track_id limit 1), + 'download_conditions', download_conditions, + 'stream_conditions', stream_conditions, + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified + ) + ) + FROM tracks + JOIN aggregate_track USING (track_id) + JOIN users ON owner_id = user_id + JOIN aggregate_user USING (user_id) + WHERE tracks.is_unlisted = false + AND tracks.is_delete = false + AND tracks.is_available = true + AND users.is_available = true + AND users.is_deactivated = false + + -- LIMIT 1000 + `, +} diff --git a/esindexer/user_indexer.go b/esindexer/user_indexer.go deleted file mode 100644 index 3e9e5f89..00000000 --- a/esindexer/user_indexer.go +++ /dev/null @@ -1,72 +0,0 @@ -package esindexer - -/* - -stage: -http://35.239.100.60:21302 - -prod: -http://35.238.44.255:21302 - -*/ - -type UserIndexer struct { - *BaseIndexer -} - -func (ui *UserIndexer) createIndex() error { - mapping := `` - return ui.BaseIndexer.createIndex("users", mapping) -} - -func (ui *UserIndexer) indexAll() error { - sql := ` - SELECT - user_id, - json_build_object( - 'name', name, - 'handle', handle, - 'bio', bio, - 'location', location, - 'created_at', created_at, - 'updated_at', updated_at, - 'blocknumber', users.blocknumber, - 'is_verified', is_verified, - - 'track_count', track_count, - 'playlist_count', playlist_count, - 'follower_count', follower_count, - 'repost_count', repost_count, - 'track_save_count', track_save_count, - 'supporter_count', supporter_count, - 'supporting_count', supporting_count, - 'dominant_genre', dominant_genre, - 'dominant_genre_count', dominant_genre_count, - - 'tracks', ( - SELECT json_agg( - json_build_object( - 'title', title, - 'genre', genre, - 'mood', mood, - 'tags', string_to_array(tags, ',') - - -- todo: more track fields - ) - ) - FROM tracks - WHERE owner_id = users.user_id - ) - ) - FROM users - JOIN aggregate_user USING (user_id) - WHERE is_deactivated = false - AND is_available = true - AND blocknumber > $1 - ORDER BY users.blocknumber ASC - - -- LIMIT 1000 - ` - - return ui.bulkIndexQuery("users", sql) -} diff --git a/esindexer/users_index.go b/esindexer/users_index.go new file mode 100644 index 00000000..952dc563 --- /dev/null +++ b/esindexer/users_index.go @@ -0,0 +1,48 @@ +package esindexer + +var userConfig = collectionConfig{ + idColumn: "user_id", + sql: ` + SELECT + user_id, + json_build_object( + 'name', name, + 'handle', handle, + 'bio', bio, + 'location', location, + 'created_at', created_at, + 'updated_at', updated_at, + 'blocknumber', users.blocknumber, + 'is_verified', is_verified, + + 'track_count', track_count, + 'playlist_count', playlist_count, + 'follower_count', follower_count, + 'repost_count', repost_count, + 'track_save_count', track_save_count, + 'supporter_count', supporter_count, + 'supporting_count', supporting_count, + 'dominant_genre', dominant_genre, + 'dominant_genre_count', dominant_genre_count, + + 'tracks', ( + SELECT json_agg( + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'tags', string_to_array(tags, ',') + + -- todo: more track fields + ) + ) + FROM tracks + WHERE owner_id = users.user_id + ) + ) + FROM users + JOIN aggregate_user USING (user_id) + WHERE is_deactivated = false + AND is_available = true + `, +} From e14a4748e6c88ff3418da21332ce7c180c03f9fb Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Sat, 21 Jun 2025 00:41:55 -0400 Subject: [PATCH 22/30] es-indexer listens to NOTIFY and re-indexes documents. Need some batching... --- esindexer/indexer.go | 78 +++++++++++-------- .../listen.go => indexer_listen.go} | 40 +++++----- esindexer/reindex.go | 30 +++++-- esindexer/socials_index.go | 4 +- esindexer/tracks_index.go | 6 +- esindexer/users_index.go | 3 +- 6 files changed, 93 insertions(+), 68 deletions(-) rename esindexer/{listen_demo/listen.go => indexer_listen.go} (75%) diff --git a/esindexer/indexer.go b/esindexer/indexer.go index 79940ec4..1e7c0f64 100644 --- a/esindexer/indexer.go +++ b/esindexer/indexer.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "strconv" "strings" "github.com/elastic/go-elasticsearch/v8" @@ -28,49 +29,68 @@ var collectionConfigs = map[string]collectionConfig{ type EsIndexer struct { pool *pgxpool.Pool esc *elasticsearch.Client - // bulk esutil.BulkIndexer + bulk esutil.BulkIndexer drop bool } -func (base *EsIndexer) createIndex(indexName string) error { - if base.drop { - _, err := base.esc.Indices.Delete([]string{indexName}) +func (indexer *EsIndexer) createIndex(collection string) error { + cc := collectionConfigs[collection] + + if indexer.drop { + _, err := indexer.esc.Indices.Delete([]string{cc.indexName}) if err != nil { - fmt.Println("drop error", indexName, err) + fmt.Println("drop error", cc.indexName, err) } } - cc := collectionConfigs[indexName] - - res, err := base.esc.Indices.Create( - indexName, - base.esc.Indices.Create.WithBody( + res, err := indexer.esc.Indices.Create( + cc.indexName, + indexer.esc.Indices.Create.WithBody( strings.NewReader(cc.mapping), ), ) if err != nil { - fmt.Println("create index error", indexName, err) + fmt.Println("create index error", cc.indexName, err) return err } - fmt.Println("created index", indexName) + fmt.Println("created index", cc.indexName) return res.Body.Close() } -func (base *EsIndexer) indexAll(indexName string) error { - cc := collectionConfigs[indexName] +func (indexer *EsIndexer) indexAll(collection string) error { + cc := collectionConfigs[collection] - ctx := context.Background() - bulk, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{ - Client: base.esc, - NumWorkers: 2, - Refresh: "true", - }) + err := indexer.indexSql(cc.indexName, cc.sql) if err != nil { - log.Fatalf("Error creating the indexer: %s", err) + return err } - rows, err := base.pool.Query(ctx, cc.sql) + fmt.Printf("stats: %s %+v \n", collection, indexer.bulk.Stats()) + + return nil +} + +func (indexer *EsIndexer) indexIds(collection string, ids ...int64) error { + cc := collectionConfigs[collection] + stringIds := make([]string, len(ids)) + for idx, id := range ids { + stringIds[idx] = strconv.Itoa(int(id)) + } + + sql := fmt.Sprintf("%s WHERE %s IN (%s)", + cc.sql, + cc.idColumn, + strings.Join(stringIds, ",")) + + return indexer.indexSql(cc.indexName, sql) +} + +func (indexer *EsIndexer) indexSql(indexName, sql string) error { + + ctx := context.Background() + + rows, err := indexer.pool.Query(ctx, sql) if err != nil { return err } @@ -84,7 +104,7 @@ func (base *EsIndexer) indexAll(indexName string) error { continue } - err = bulk.Add(ctx, esutil.BulkIndexerItem{ + err = indexer.bulk.Add(ctx, esutil.BulkIndexerItem{ Action: "index", Index: indexName, DocumentID: fmt.Sprintf("%d", id), @@ -107,15 +127,5 @@ func (base *EsIndexer) indexAll(indexName string) error { } } - if err := rows.Err(); err != nil { - fmt.Println("rows error:", err) - } - - if err := bulk.Close(context.Background()); err != nil { - log.Fatalf("Unexpected error: %s", err) - } - - fmt.Printf("stats: %s %+v \n", indexName, bulk.Stats()) - - return nil + return rows.Err() } diff --git a/esindexer/listen_demo/listen.go b/esindexer/indexer_listen.go similarity index 75% rename from esindexer/listen_demo/listen.go rename to esindexer/indexer_listen.go index eae4bec3..43111cab 100644 --- a/esindexer/listen_demo/listen.go +++ b/esindexer/indexer_listen.go @@ -1,4 +1,4 @@ -package main +package esindexer import ( "context" @@ -15,43 +15,43 @@ import ( _ "github.com/joho/godotenv/autoload" ) -func main() { +func (indexer *EsIndexer) listen() error { ctx := context.Background() listener := &pgxlisten.Listener{ - // Provide a pgx connection for listening Connect: func(ctx context.Context) (*pgx.Conn, error) { + // Provide a pgx connection for listening return pgx.Connect(ctx, os.Getenv("discoveryDbUrl")) }, LogError: func(ctx context.Context, err error) { log.Println("Listener error:", err) }, - // Reconnect after 10s on error ReconnectDelay: 10 * time.Second, } - // generic handler to just print NOTIFY payload - // logNotify := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { - // fmt.Println(notification.Channel, notification.Payload) - // return nil - // }) - + // todo: these should probably queue IDs for N seconds + // and then call index + // especially with the aggregate_user batch update... + // that touches lots of rows.. + // don't want to be doing those one at a time. userHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { id := gjson.Get(notification.Payload, "user_id").Int() fmt.Println("reindex user:", notification.Channel, id) - // userIndexer.reindexId(id) + indexer.indexIds("users", id) return nil }) trackHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { id := gjson.Get(notification.Payload, "track_id").Int() fmt.Println("reindex track:", notification.Channel, id) + indexer.indexIds("tracks", id) return nil }) playlistHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { id := gjson.Get(notification.Payload, "playlist_id").Int() - fmt.Println("reindex track:", notification.Channel, id) + fmt.Println("reindex playlist:", notification.Channel, id) + indexer.indexIds("playlists", id) return nil }) @@ -65,7 +65,8 @@ func main() { listener.Handle("follows", pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { followerId := gjson.Get(notification.Payload, "follower_user_id").Int() followeeId := gjson.Get(notification.Payload, "followee_user_id").Int() - fmt.Println("reindex socials:", followerId, "add follow", followeeId) + fmt.Println("____ reindex socials:", followerId, "add follow", followeeId) + indexer.indexIds("socials", followerId) return nil })) @@ -73,7 +74,8 @@ func main() { userId := gjson.Get(notification.Payload, "user_id").Int() isTrack := gjson.Get(notification.Payload, "repost_type").String() == "track" id := gjson.Get(notification.Payload, "repost_item_id").Int() - fmt.Println("reindex socials:", userId, "add repost", isTrack, id) + fmt.Println("___ reindex socials:", userId, "add repost", isTrack, id) + indexer.indexIds("socials", userId) return nil })) @@ -81,18 +83,14 @@ func main() { userId := gjson.Get(notification.Payload, "user_id").Int() isTrack := gjson.Get(notification.Payload, "save_type").String() == "track" id := gjson.Get(notification.Payload, "save_item_id").Int() - fmt.Println("reindex socials:", userId, "add save", isTrack, id) + fmt.Println("____: reindex socials:", userId, "add save", isTrack, id) + indexer.indexIds("socials", userId) return nil })) - // listener.Handle("reposts", logNotify) - // listener.Handle("saves", logNotify) - // listener.Handle("listens", logNotify) // listener.Handle("aggregate_plays", logNotify) fmt.Println("🚀 Starting listener...") - if err := listener.Listen(ctx); err != nil { - log.Fatalf("Listener terminated: %v", err) - } + return listener.Listen(ctx) } diff --git a/esindexer/reindex.go b/esindexer/reindex.go index 9cc9787b..9406a031 100644 --- a/esindexer/reindex.go +++ b/esindexer/reindex.go @@ -7,6 +7,7 @@ import ( "bridgerton.audius.co/config" "github.com/elastic/go-elasticsearch/v8" + "github.com/elastic/go-elasticsearch/v8/esutil" "github.com/jackc/pgx/v5/pgxpool" "github.com/tidwall/sjson" ) @@ -58,27 +59,46 @@ func reindexCollection(i *EsIndexer, collection string) { func Reindex(pool *pgxpool.Pool, esc *elasticsearch.Client, drop bool, collections ...string) { - baseIndexer := &EsIndexer{ + bulk, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{ + Client: esc, + NumWorkers: 2, + Refresh: "true", + }) + if err != nil { + log.Fatalf("Error creating the indexer: %s", err) + } + + esIndexer := &EsIndexer{ pool, esc, + bulk, drop, } + // this is just a "listen" demo for now... + // this will block forever + // todo: need to figure out if this runs after any re-index, or concurrently... + if slices.Contains(collections, "listen") { + esIndexer.listen() + } + reindexAll := len(collections) == 0 || slices.Contains(collections, "all") if reindexAll || slices.Contains(collections, "playlists") { - reindexCollection(baseIndexer, "playlists") + reindexCollection(esIndexer, "playlists") } if reindexAll || slices.Contains(collections, "tracks") { - reindexCollection(baseIndexer, "tracks") + reindexCollection(esIndexer, "tracks") } if reindexAll || slices.Contains(collections, "users") { - reindexCollection(baseIndexer, "users") + reindexCollection(esIndexer, "users") } if reindexAll || slices.Contains(collections, "socials") { - reindexCollection(baseIndexer, "socials") + reindexCollection(esIndexer, "socials") } + esIndexer.bulk.Close(context.Background()) + } func ReindexLegacy(drop bool, collections ...string) { diff --git a/esindexer/socials_index.go b/esindexer/socials_index.go index e4100983..7fc32225 100644 --- a/esindexer/socials_index.go +++ b/esindexer/socials_index.go @@ -79,8 +79,6 @@ var socialsConfig = collectionConfig{ ) as doc from aggregate_user users - - -- todo remove - LIMIT 1000 + where 1=1 `, } diff --git a/esindexer/tracks_index.go b/esindexer/tracks_index.go index 94d6ae49..56872e63 100644 --- a/esindexer/tracks_index.go +++ b/esindexer/tracks_index.go @@ -1,8 +1,8 @@ package esindexer var tracksConfig = collectionConfig{ - // indexName: , - idColumn: "track_id", + indexName: "tracks", + idColumn: "track_id", mapping: ` { "mappings": { @@ -49,7 +49,5 @@ var tracksConfig = collectionConfig{ AND tracks.is_available = true AND users.is_available = true AND users.is_deactivated = false - - -- LIMIT 1000 `, } diff --git a/esindexer/users_index.go b/esindexer/users_index.go index 952dc563..f9f53857 100644 --- a/esindexer/users_index.go +++ b/esindexer/users_index.go @@ -1,7 +1,8 @@ package esindexer var userConfig = collectionConfig{ - idColumn: "user_id", + indexName: "users", + idColumn: "user_id", sql: ` SELECT user_id, From b57cc64f6aa4cca7498d4dc31b56f52a8a4df7f4 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Mon, 23 Jun 2025 12:40:08 -0400 Subject: [PATCH 23/30] scoring tweaks --- Makefile | 19 ++++++------------- api/searchv1/dsl_helpers.go | 6 +++--- api/searchv1/track_search.go | 11 ++++++++++- api/searchv1/user_search.go | 5 +++++ api/v1_search.go | 2 ++ esindexer/indexer_listen.go | 5 ++++- 6 files changed, 30 insertions(+), 18 deletions(-) diff --git a/Makefile b/Makefile index 31c78716..25c0b3ff 100644 --- a/Makefile +++ b/Makefile @@ -6,24 +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' - -esindexer:: - mkdir -p build/production - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/production/bridge-amd64 - rsync -ravz build/production/ prod-elasticsearch:esindexer + 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 diff --git a/api/searchv1/dsl_helpers.go b/api/searchv1/dsl_helpers.go index 0dae1ede..afdad4f8 100644 --- a/api/searchv1/dsl_helpers.go +++ b/api/searchv1/dsl_helpers.go @@ -32,14 +32,14 @@ func BuildFunctionScoreDSL(scoreField string, innerQuery map[string]any) string "query": { "function_score": { "query": %s, - "boost_mode": "sum", - "score_mode": "sum", + "boost_mode": "multiply", + "score_mode": "multiply", "functions": [ { "field_value_factor": { "field": %q, "factor": 100, - "modifier": "log1p", + "modifier": "ln2p", "missing": 0 } } diff --git a/api/searchv1/track_search.go b/api/searchv1/track_search.go index 7965fe82..eeed186d 100644 --- a/api/searchv1/track_search.go +++ b/api/searchv1/track_search.go @@ -27,7 +27,16 @@ func (q *TrackSearchQuery) Map() map[string]any { 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", "user.handle", "user.name", "tags").Type(esquery.MatchTypeBoolPrefix), + 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()) diff --git a/api/searchv1/user_search.go b/api/searchv1/user_search.go index 8a6a35e3..7d4ddf66 100644 --- a/api/searchv1/user_search.go +++ b/api/searchv1/user_search.go @@ -20,6 +20,11 @@ func (q *UserSearchQuery) Map() map[string]any { builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tracks.tags").Type(esquery.MatchTypeBoolPrefix)) } else if q.Query != "" { builder.Must(esquery.MultiMatch(q.Query).Fields("name", "handle").Type(esquery.MatchTypeBoolPrefix)) + + // for exact title match + builder.Should( + esquery.MultiMatch().Query(q.Query).Fields("name", "handle").Operator(esquery.OperatorAnd).Type(esquery.MatchTypePhrasePrefix), + ) } else { builder.Must(esquery.MatchAll()) } diff --git a/api/v1_search.go b/api/v1_search.go index 4d05aa9c..ebf93e3a 100644 --- a/api/v1_search.go +++ b/api/v1_search.go @@ -163,6 +163,7 @@ func (app *ApiServer) searchPlaylists(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) Ids: playlistsIds, MyID: myId, }, + OmitTracks: true, }) return playlists, err } @@ -193,6 +194,7 @@ func (app *ApiServer) searchAlbums(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) { Ids: playlistsIds, MyID: myId, }, + OmitTracks: true, }) return playlists, err } diff --git a/esindexer/indexer_listen.go b/esindexer/indexer_listen.go index 43111cab..ccd267ff 100644 --- a/esindexer/indexer_listen.go +++ b/esindexer/indexer_listen.go @@ -88,7 +88,10 @@ func (indexer *EsIndexer) listen() error { return nil })) - // listener.Handle("listens", logNotify) + // this fires all the time... + // but we're not even indexing play_count atm... + // todo: index play count + // also... we might not need to update this so often... // listener.Handle("aggregate_plays", logNotify) fmt.Println("🚀 Starting listener...") From 801f3f0eeeadc66fed832ce226a038080532e8b8 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Mon, 23 Jun 2025 13:52:25 -0400 Subject: [PATCH 24/30] Fix + improve explore pages --- api/searchv1/playlist_search.go | 12 ++++++++++-- api/searchv1/track_search.go | 4 ++-- api/searchv1/user_search.go | 10 ++++++++++ api/v1_search.go | 1 + api/v1_search_test.go | 10 +++++----- 5 files changed, 28 insertions(+), 9 deletions(-) diff --git a/api/searchv1/playlist_search.go b/api/searchv1/playlist_search.go index 963bcb6d..f6d4be18 100644 --- a/api/searchv1/playlist_search.go +++ b/api/searchv1/playlist_search.go @@ -30,11 +30,19 @@ func (q *PlaylistSearchQuery) Map() map[string]any { builder.Filter(esquery.Term("is_album", q.IsAlbum)) if len(q.Genres) > 0 { - builder.Filter(esquery.Terms("tracks.genre", toAnySlice(q.Genres)...)) + 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", toAnySlice(q.Moods)...)) + 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 { diff --git a/api/searchv1/track_search.go b/api/searchv1/track_search.go index eeed186d..6a2329e6 100644 --- a/api/searchv1/track_search.go +++ b/api/searchv1/track_search.go @@ -54,11 +54,11 @@ func (q *TrackSearchQuery) Map() map[string]any { } if len(q.Genres) > 0 { - builder.Filter(esquery.Terms("genre", toAnySlice(q.Genres)...)) + builder.Filter(esquery.Terms("genre.keyword", toAnySlice(q.Genres)...)) } if len(q.Moods) > 0 { - builder.Filter(esquery.Terms("mood", toAnySlice(q.Moods)...)) + builder.Filter(esquery.Terms("mood.keyword", toAnySlice(q.Moods)...)) } if len(q.MusicalKeys) > 0 { diff --git a/api/searchv1/user_search.go b/api/searchv1/user_search.go index 7d4ddf66..238472ab 100644 --- a/api/searchv1/user_search.go +++ b/api/searchv1/user_search.go @@ -10,6 +10,7 @@ type UserSearchQuery struct { Query string `json:"query"` IsVerified bool `json:"is_verified"` IsTagSearch bool + Genres []string MyID int32 `json:"my_id"` } @@ -29,6 +30,15 @@ func (q *UserSearchQuery) Map() map[string]any { builder.Must(esquery.MatchAll()) } + if len(q.Genres) > 0 { + builder.Must(esquery.Range("track_count").Gt(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 profiles higher if they have a larger proportion of genre + for _, value := range q.Genres { + builder.Should(esquery.Match("tracks.genre", value)).Boost(10) + } + } + if q.MyID > 0 { builder.Should(esquery.CustomQuery(map[string]any{ "terms": map[string]any{ diff --git a/api/v1_search.go b/api/v1_search.go index ebf93e3a..626e8c89 100644 --- a/api/v1_search.go +++ b/api/v1_search.go @@ -89,6 +89,7 @@ func (app *ApiServer) searchUsers(c *fiber.Ctx) ([]dbv1.FullUser, error) { Query: c.Query("query"), IsVerified: c.QueryBool("is_verified"), IsTagSearch: isTagSearch, + Genres: queryMutli(c, "genre"), MyID: myId, } diff --git a/api/v1_search_test.go b/api/v1_search_test.go index fe34304f..e14e5bea 100644 --- a/api/v1_search_test.go +++ b/api/v1_search_test.go @@ -201,7 +201,7 @@ func TestSearch(t *testing.T) { // tracks: filter by genre + mood + bpm { - status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap") + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ "data.tracks.#": 2, @@ -267,7 +267,7 @@ func TestSearch(t *testing.T) { } { - status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&bpm_min=90") + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap&bpm_min=90") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ "data.tracks.#": 1, @@ -276,7 +276,7 @@ func TestSearch(t *testing.T) { } { - status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&bpm_max=90") + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap&bpm_max=90") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ "data.tracks.#": 1, @@ -285,7 +285,7 @@ func TestSearch(t *testing.T) { } { - status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&genre=jazz") + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap&genre=Jazz") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ "data.tracks.#": 3, @@ -293,7 +293,7 @@ func TestSearch(t *testing.T) { } { - status, body := testGet(t, app, "/v1/search/autocomplete?genre=trap&genre=jazz&mood=uplifting") + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap&genre=Jazz&mood=Uplifting") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ "data.tracks.#": 2, From a4ab5a9138d3411a1b616f9194cebb2690f6a218 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Tue, 24 Jun 2025 10:09:36 -0400 Subject: [PATCH 25/30] es-indexer listener batches changes in 10s interval. Also uses painless to "patch" social documents. --- esindexer/indexer.go | 69 +++++++++++++++++++++++- esindexer/indexer_listen.go | 91 +++++++++++++++++++++++++------- esindexer/indexer_listen_test.go | 23 ++++++++ esindexer/reindex.go | 19 ++++++- 4 files changed, 181 insertions(+), 21 deletions(-) create mode 100644 esindexer/indexer_listen_test.go diff --git a/esindexer/indexer.go b/esindexer/indexer.go index 1e7c0f64..36eacf3c 100644 --- a/esindexer/indexer.go +++ b/esindexer/indexer.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "log/slog" "strconv" "strings" @@ -72,17 +73,23 @@ func (indexer *EsIndexer) indexAll(collection string) error { } func (indexer *EsIndexer) indexIds(collection string, ids ...int64) error { + if len(ids) == 0 { + return nil + } + cc := collectionConfigs[collection] stringIds := make([]string, len(ids)) for idx, id := range ids { stringIds[idx] = strconv.Itoa(int(id)) } - sql := fmt.Sprintf("%s WHERE %s IN (%s)", + sql := fmt.Sprintf("%s AND %s IN (%s)", cc.sql, cc.idColumn, strings.Join(stringIds, ",")) + slog.Info("index", "collection", collection, "ids", ids) + return indexer.indexSql(cc.indexName, sql) } @@ -129,3 +136,63 @@ func (indexer *EsIndexer) indexSql(indexName, sql string) error { return rows.Err() } + +// this uses painless to 'patch' a `socials` doc to add / remove an entity ID from a list of ids. +// without forcing postgres to re-do the socials query from scratch. +// If missing (i.e. for a new user) it will fall back to re-doing from scratch. +// This might be a "too clever by half" type of thing... in which case, the listener could just use `indexIds` +// like the other collections +func (indexer *EsIndexer) scriptedUpdateSocial(userId int64, fieldName string, entityId int64, isDelete bool) { + painlessAddEntity := ` + def user = ctx._source; + if (!user[params.fieldName].contains(params.entityId)) { + user[params.fieldName].add(params.entityId); + } else { + ctx.op = 'noop' + } + ` + + painlessRemoveEntity := ` + def user = ctx._source; + def idx = user[params.fieldName].indexOf(params.entityId); + if (idx > -1) { + user[params.fieldName].remove(idx); + } else { + ctx.op = 'noop' + } + ` + + script := painlessAddEntity + if isDelete { + script = painlessRemoveEntity + } + + resp, err := indexer.esc.Update( + "socials", + fmt.Sprintf("%d", userId), + strings.NewReader(fmt.Sprintf(`{ + "script": { + "source": %q, + "lang": "painless", + "params": { + "fieldName": %q, + "entityId": %d + } + } + }`, script, fieldName, entityId)), + ) + defer resp.Body.Close() + + if err != nil { + log.Printf("scripted update error: %v", err) + } else if resp.StatusCode != 200 { + if err := indexer.indexIds("socials", userId); err != nil { + slog.Error("socials indexIds failed", "user", userId, "field", fieldName, "id", entityId, "err", err) + } else { + slog.Info("socials indexIds", "user", userId, "field", fieldName, "id", entityId) + } + } else { + slog.Info("social update", "user", userId, "field", fieldName, "id", entityId) + } + +} diff --git a/esindexer/indexer_listen.go b/esindexer/indexer_listen.go index ccd267ff..65d88b1e 100644 --- a/esindexer/indexer_listen.go +++ b/esindexer/indexer_listen.go @@ -5,6 +5,8 @@ import ( "fmt" "log" "os" + "slices" + "sync" "time" "github.com/jackc/pgx/v5" @@ -15,8 +17,34 @@ import ( _ "github.com/joho/godotenv/autoload" ) -func (indexer *EsIndexer) listen() error { - ctx := context.Background() +type pendingChanges struct { + sync.Mutex + idMap map[string][]int64 +} + +func (pending *pendingChanges) enqueue(collection string, id int64) { + pending.Lock() + defer pending.Unlock() + + if _, ok := pending.idMap[collection]; !ok { + pending.idMap[collection] = []int64{} + } + + if !slices.Contains(pending.idMap[collection], id) { + pending.idMap[collection] = append(pending.idMap[collection], id) + } +} + +func (pending *pendingChanges) take() map[string][]int64 { + pending.Lock() + defer pending.Unlock() + + idMap := pending.idMap + pending.idMap = map[string][]int64{} + return idMap +} + +func (indexer *EsIndexer) listen(ctx context.Context) error { listener := &pgxlisten.Listener{ Connect: func(ctx context.Context) (*pgx.Conn, error) { @@ -29,29 +57,26 @@ func (indexer *EsIndexer) listen() error { ReconnectDelay: 10 * time.Second, } - // todo: these should probably queue IDs for N seconds - // and then call index - // especially with the aggregate_user batch update... - // that touches lots of rows.. - // don't want to be doing those one at a time. + pending := &pendingChanges{ + idMap: map[string][]int64{}, + } + + // entity changes get batched up and processed every N seconds userHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { id := gjson.Get(notification.Payload, "user_id").Int() - fmt.Println("reindex user:", notification.Channel, id) - indexer.indexIds("users", id) + pending.enqueue("users", id) return nil }) trackHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { id := gjson.Get(notification.Payload, "track_id").Int() - fmt.Println("reindex track:", notification.Channel, id) - indexer.indexIds("tracks", id) + pending.enqueue("tracks", id) return nil }) playlistHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { id := gjson.Get(notification.Payload, "playlist_id").Int() - fmt.Println("reindex playlist:", notification.Channel, id) - indexer.indexIds("playlists", id) + pending.enqueue("playlists", id) return nil }) @@ -62,11 +87,13 @@ func (indexer *EsIndexer) listen() error { listener.Handle("playlists", playlistHandler) listener.Handle("playlist_track", playlistHandler) + // "socials" changes do update via a painless script listener.Handle("follows", pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { followerId := gjson.Get(notification.Payload, "follower_user_id").Int() followeeId := gjson.Get(notification.Payload, "followee_user_id").Int() - fmt.Println("____ reindex socials:", followerId, "add follow", followeeId) - indexer.indexIds("socials", followerId) + isDelete := gjson.Get(notification.Payload, "is_delete").Bool() + + indexer.scriptedUpdateSocial(followerId, "following_user_ids", followeeId, isDelete) return nil })) @@ -74,8 +101,14 @@ func (indexer *EsIndexer) listen() error { userId := gjson.Get(notification.Payload, "user_id").Int() isTrack := gjson.Get(notification.Payload, "repost_type").String() == "track" id := gjson.Get(notification.Payload, "repost_item_id").Int() - fmt.Println("___ reindex socials:", userId, "add repost", isTrack, id) - indexer.indexIds("socials", userId) + isDelete := gjson.Get(notification.Payload, "is_delete").Bool() + + field := "reposted_playlist_ids" + if isTrack { + field = "reposted_track_ids" + } + + indexer.scriptedUpdateSocial(userId, field, id, isDelete) return nil })) @@ -83,8 +116,14 @@ func (indexer *EsIndexer) listen() error { userId := gjson.Get(notification.Payload, "user_id").Int() isTrack := gjson.Get(notification.Payload, "save_type").String() == "track" id := gjson.Get(notification.Payload, "save_item_id").Int() - fmt.Println("____: reindex socials:", userId, "add save", isTrack, id) - indexer.indexIds("socials", userId) + isDelete := gjson.Get(notification.Payload, "is_delete").Bool() + + field := "saved_playlist_ids" + if isTrack { + field = "saved_track_ids" + } + + indexer.scriptedUpdateSocial(userId, field, id, isDelete) return nil })) @@ -94,6 +133,20 @@ func (indexer *EsIndexer) listen() error { // also... we might not need to update this so often... // listener.Handle("aggregate_plays", logNotify) + go func() { + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() + for range ticker.C { + idMap := pending.take() + for collection, ids := range idMap { + if err := indexer.indexIds(collection, ids...); err != nil { + log.Printf("Error indexing %s: %v", collection, err) + } + } + } + }() + fmt.Println("🚀 Starting listener...") return listener.Listen(ctx) + } diff --git a/esindexer/indexer_listen_test.go b/esindexer/indexer_listen_test.go new file mode 100644 index 00000000..372ca6cf --- /dev/null +++ b/esindexer/indexer_listen_test.go @@ -0,0 +1,23 @@ +package esindexer + +import ( + "testing" + + "github.com/test-go/testify/require" +) + +func TestPending(t *testing.T) { + pending := &pendingChanges{ + idMap: map[string][]int64{}, + } + + pending.enqueue("users", 1) + pending.enqueue("users", 1) + pending.enqueue("users", 2) + pending.enqueue("tracks", 3) + + idMap := pending.take() + require.Equal(t, []int64{1, 2}, idMap["users"]) + require.Empty(t, pending.idMap["users"]) + +} diff --git a/esindexer/reindex.go b/esindexer/reindex.go index 9406a031..c17b04a3 100644 --- a/esindexer/reindex.go +++ b/esindexer/reindex.go @@ -2,8 +2,12 @@ package esindexer import ( "context" + "fmt" "log" + "os" + "os/signal" "slices" + "syscall" "bridgerton.audius.co/config" "github.com/elastic/go-elasticsearch/v8" @@ -79,7 +83,20 @@ func Reindex(pool *pgxpool.Pool, esc *elasticsearch.Client, drop bool, collectio // this will block forever // todo: need to figure out if this runs after any re-index, or concurrently... if slices.Contains(collections, "listen") { - esIndexer.listen() + ctx, cancel := context.WithCancel(context.Background()) + + // Listen for Ctrl+C (SIGINT) and call cancel when received + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) + go func() { + <-sigCh + fmt.Println("Listen exit") + cancel() + os.Exit(0) + }() + + esIndexer.listen(ctx) + } reindexAll := len(collections) == 0 || slices.Contains(collections, "all") From e8f95ead74118bf11192572aeaf5ad82da6f88ea Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Tue, 24 Jun 2025 10:38:38 -0400 Subject: [PATCH 26/30] rename v1SearchFull handler func --- api/server.go | 6 +++--- api/v1_search.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/api/server.go b/api/server.go index 67a41dcc..018453d6 100644 --- a/api/server.go +++ b/api/server.go @@ -343,9 +343,9 @@ func NewApiServer(config config.Config) *ApiServer { g.Get("/playlists/:playlistId/favorites", app.v1PlaylistFavorites) // Search - g.Get("/search/autocomplete", app.v1SearchAutocomplete) - g.Get("/search/full", app.v1SearchAutocomplete) - g.Get("/search/tags", app.v1SearchAutocomplete) + g.Get("/search/autocomplete", app.v1SearchFull) + g.Get("/search/full", app.v1SearchFull) + g.Get("/search/tags", app.v1SearchFull) // Developer Apps g.Get("/developer_apps/:address", app.v1DeveloperApps) diff --git a/api/v1_search.go b/api/v1_search.go index 626e8c89..c03d2b5c 100644 --- a/api/v1_search.go +++ b/api/v1_search.go @@ -9,7 +9,7 @@ import ( "golang.org/x/sync/errgroup" ) -func (app *ApiServer) v1SearchAutocomplete(c *fiber.Ctx) error { +func (app *ApiServer) v1SearchFull(c *fiber.Ctx) error { kind := c.Query("kind", "all") g := errgroup.Group{} From f772fb8973015b0c64273c6dd5a0d267b15a299a Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Tue, 24 Jun 2025 10:42:01 -0400 Subject: [PATCH 27/30] savings: only personalize results for "full" endpoint --- api/v1_search.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/api/v1_search.go b/api/v1_search.go index c03d2b5c..667b4fba 100644 --- a/api/v1_search.go +++ b/api/v1_search.go @@ -81,6 +81,7 @@ func (app *ApiServer) v1SearchFull(c *fiber.Ctx) error { func (app *ApiServer) searchUsers(c *fiber.Ctx) ([]dbv1.FullUser, error) { isTagSearch := strings.Contains(c.Route().Path, "search/tags") + isFullSearch := strings.Contains(c.Route().Path, "search/full") limit := c.QueryInt("limit", 10) offset := c.QueryInt("offset", 0) myId := app.getMyId(c) @@ -98,6 +99,11 @@ func (app *ApiServer) searchUsers(c *fiber.Ctx) ([]dbv1.FullUser, error) { return nil, err } + // savings: only personalize results for "full" endpoint + if !isFullSearch { + myId = 0 + } + users, err := app.queries.FullUsers(c.Context(), dbv1.GetUsersParams{ Ids: userIds, MyID: myId, @@ -107,6 +113,7 @@ func (app *ApiServer) searchUsers(c *fiber.Ctx) ([]dbv1.FullUser, error) { func (app *ApiServer) searchTracks(c *fiber.Ctx) ([]dbv1.FullTrack, error) { isTagSearch := strings.Contains(c.Route().Path, "search/tags") + isFullSearch := strings.Contains(c.Route().Path, "search/full") limit := c.QueryInt("limit", 10) offset := c.QueryInt("offset", 0) myId := app.getMyId(c) @@ -130,6 +137,11 @@ func (app *ApiServer) searchTracks(c *fiber.Ctx) ([]dbv1.FullTrack, error) { return nil, err } + // savings: only personalize results for "full" endpoint + if !isFullSearch { + myId = 0 + } + tracks, err := app.queries.FullTracks(c.Context(), dbv1.FullTracksParams{ GetTracksParams: dbv1.GetTracksParams{ Ids: tracksIds, @@ -141,6 +153,7 @@ func (app *ApiServer) searchTracks(c *fiber.Ctx) ([]dbv1.FullTrack, error) { func (app *ApiServer) searchPlaylists(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) { isTagSearch := strings.Contains(c.Route().Path, "search/tags") + isFullSearch := strings.Contains(c.Route().Path, "search/full") limit := c.QueryInt("limit", 10) offset := c.QueryInt("offset", 0) myId := app.getMyId(c) @@ -159,6 +172,11 @@ func (app *ApiServer) searchPlaylists(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) return nil, err } + // savings: only personalize results for "full" endpoint + if !isFullSearch { + myId = 0 + } + playlists, err := app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ GetPlaylistsParams: dbv1.GetPlaylistsParams{ Ids: playlistsIds, @@ -171,6 +189,7 @@ func (app *ApiServer) searchPlaylists(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) func (app *ApiServer) searchAlbums(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) { isTagSearch := strings.Contains(c.Route().Path, "search/tags") + isFullSearch := strings.Contains(c.Route().Path, "search/full") limit := c.QueryInt("limit", 10) offset := c.QueryInt("offset", 0) myId := app.getMyId(c) @@ -190,6 +209,11 @@ func (app *ApiServer) searchAlbums(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) { return nil, err } + // savings: only personalize results for "full" endpoint + if !isFullSearch { + myId = 0 + } + playlists, err := app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ GetPlaylistsParams: dbv1.GetPlaylistsParams{ Ids: playlistsIds, From 0f0662b708f4b0a08b239e17d69b34b1542fed28 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Tue, 24 Jun 2025 11:58:20 -0400 Subject: [PATCH 28/30] start all containers in github tests --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b6df3439..fb5e7087 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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 From 155d66505f3870a1b8dfce7d46643e879af44856 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Wed, 25 Jun 2025 10:28:40 -0400 Subject: [PATCH 29/30] PR cleanup --- api/searchv1/dsl_helpers.go | 3 --- api/searchv1/playlist_search.go | 2 +- api/v1_search_test.go | 2 +- esindexer/indexer.go | 6 ++---- esindexer/reindex.go | 1 - static/searchtest.html | 8 ++++++-- 6 files changed, 10 insertions(+), 12 deletions(-) diff --git a/api/searchv1/dsl_helpers.go b/api/searchv1/dsl_helpers.go index afdad4f8..9a7fe3e1 100644 --- a/api/searchv1/dsl_helpers.go +++ b/api/searchv1/dsl_helpers.go @@ -48,7 +48,6 @@ func BuildFunctionScoreDSL(scoreField string, innerQuery map[string]any) string } }`, innerJson, scoreField) - // pprintJson(dsl) return dsl } @@ -76,8 +75,6 @@ func SearchAndPluck(esClient *elasticsearch.Client, index, dsl string, limit, of return nil, err } - // fmt.Println("ES BODY", index, string(body)) - result := []int32{} for _, hit := range gjson.GetBytes(body, "hits.hits").Array() { id := hit.Get("_id").Int() diff --git a/api/searchv1/playlist_search.go b/api/searchv1/playlist_search.go index f6d4be18..f131e934 100644 --- a/api/searchv1/playlist_search.go +++ b/api/searchv1/playlist_search.go @@ -22,7 +22,7 @@ func (q *PlaylistSearchQuery) Map() map[string]any { 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", "user.handle", "user.name", "tracks.tags").Type(esquery.MatchTypeBoolPrefix)) + builder.Must(esquery.MultiMatch().Query(q.Query).Fields("title^10", "user.handle", "user.name", "tracks.tags").Type(esquery.MatchTypeBoolPrefix)) } else { builder.Must(esquery.MatchAll()) } diff --git a/api/v1_search_test.go b/api/v1_search_test.go index e14e5bea..1b1338c5 100644 --- a/api/v1_search_test.go +++ b/api/v1_search_test.go @@ -222,7 +222,7 @@ func TestSearch(t *testing.T) { status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo+sun") require.Equal(t, 200, status) jsonAssert(t, body, map[string]any{ - // "data.tracks.#": 3, + "data.tracks.#": 3, "data.tracks.0.title": "sunny side", }) } diff --git a/esindexer/indexer.go b/esindexer/indexer.go index 36eacf3c..c35ae276 100644 --- a/esindexer/indexer.go +++ b/esindexer/indexer.go @@ -67,7 +67,7 @@ func (indexer *EsIndexer) indexAll(collection string) error { return err } - fmt.Printf("stats: %s %+v \n", collection, indexer.bulk.Stats()) + slog.Info("index all stats", "collection", collection, "stats", indexer.bulk.Stats()) return nil } @@ -116,9 +116,7 @@ func (indexer *EsIndexer) indexSql(indexName, sql string) error { Index: indexName, DocumentID: fmt.Sprintf("%d", id), Body: strings.NewReader(doc), - OnSuccess: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem) { - // fmt.Println("index", index, id) - }, + OnSuccess: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem) {}, OnFailure: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem, err error) { if err != nil { log.Printf("ERROR: %s", err) diff --git a/esindexer/reindex.go b/esindexer/reindex.go index c17b04a3..dbb40aad 100644 --- a/esindexer/reindex.go +++ b/esindexer/reindex.go @@ -52,7 +52,6 @@ func commonIndexSettings(mapping string) string { } func reindexCollection(i *EsIndexer, collection string) { - if err := i.createIndex(collection); err != nil { panic(err) } diff --git a/static/searchtest.html b/static/searchtest.html index 86a32007..95e70828 100644 --- a/static/searchtest.html +++ b/static/searchtest.html @@ -100,7 +100,9 @@

${playlists.length} Playlists

@@ -111,7 +113,9 @@

${albums.length} albums

From 739a3570ba70265c7338be83ee5349668cc0c1e2 Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Wed, 25 Jun 2025 12:18:47 -0400 Subject: [PATCH 30/30] rename files: esindexer --- esindexer/{indexer.go => esindexer.go} | 0 esindexer/{indexer_listen.go => esindexer_listen.go} | 0 .../{indexer_listen_test.go => esindexer_listen_test.go} | 0 static/searchtest.html | 6 +++++- 4 files changed, 5 insertions(+), 1 deletion(-) rename esindexer/{indexer.go => esindexer.go} (100%) rename esindexer/{indexer_listen.go => esindexer_listen.go} (100%) rename esindexer/{indexer_listen_test.go => esindexer_listen_test.go} (100%) diff --git a/esindexer/indexer.go b/esindexer/esindexer.go similarity index 100% rename from esindexer/indexer.go rename to esindexer/esindexer.go diff --git a/esindexer/indexer_listen.go b/esindexer/esindexer_listen.go similarity index 100% rename from esindexer/indexer_listen.go rename to esindexer/esindexer_listen.go diff --git a/esindexer/indexer_listen_test.go b/esindexer/esindexer_listen_test.go similarity index 100% rename from esindexer/indexer_listen_test.go rename to esindexer/esindexer_listen_test.go diff --git a/static/searchtest.html b/static/searchtest.html index 95e70828..59aa1f56 100644 --- a/static/searchtest.html +++ b/static/searchtest.html @@ -79,7 +79,11 @@ trackResults.innerHTML = html`

${tracks.length} Tracks

    - ${tracks.map((t) => html`
  • ${t.title}
  • `)} + ${tracks.map( + (t) => html`
  • + ${t.title} +
  • ` + )}
`;