Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
898742bc53 | ||
|
|
94717399cf |
No files matched your search
@@ -10,8 +10,8 @@ require (
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0
|
||||
github.com/Nerzal/gocloak/v13 v13.9.0
|
||||
github.com/bbalet/stopwords v1.0.0
|
||||
github.com/beevik/etree v1.7.0
|
||||
github.com/blevesearch/bleve/v2 v2.6.0
|
||||
github.com/beevik/etree v1.7.1
|
||||
github.com/blevesearch/bleve/v2 v2.6.1
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible
|
||||
github.com/cenkalti/backoff/v5 v5.0.3
|
||||
github.com/coreos/go-oidc/v3 v3.20.0
|
||||
@@ -22,7 +22,7 @@ require (
|
||||
github.com/egirna/icap-client v0.1.1
|
||||
github.com/gabriel-vasile/mimetype v1.4.15
|
||||
github.com/ggwhite/go-masker v1.1.0
|
||||
github.com/go-chi/chi/v5 v5.3.1
|
||||
github.com/go-chi/chi/v5 v5.3.2
|
||||
github.com/go-chi/httprate v0.16.0
|
||||
github.com/go-chi/render v1.0.3
|
||||
github.com/go-ldap/ldap/v3 v3.4.14
|
||||
@@ -63,7 +63,7 @@ require (
|
||||
github.com/olekukonko/tablewriter v1.1.4
|
||||
github.com/onsi/ginkgo v1.16.5
|
||||
github.com/onsi/ginkgo/v2 v2.32.1
|
||||
github.com/onsi/gomega v1.42.1
|
||||
github.com/onsi/gomega v1.43.0
|
||||
github.com/open-policy-agent/opa v1.19.0
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
@@ -76,10 +76,10 @@ require (
|
||||
github.com/rs/cors v1.11.1
|
||||
github.com/rs/zerolog v1.35.1
|
||||
github.com/shamaton/msgpack/v2 v2.4.1
|
||||
github.com/sirupsen/logrus v1.10.0
|
||||
github.com/sirupsen/logrus v1.10.2
|
||||
github.com/spf13/afero v1.15.0
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/test-go/testify v1.1.4
|
||||
github.com/thejerf/suture/v4 v4.0.6
|
||||
github.com/tidwall/gjson v1.19.0
|
||||
@@ -89,14 +89,14 @@ require (
|
||||
github.com/xhit/go-simple-mail/v2 v2.16.0
|
||||
go-micro.dev/v4 v4.11.0
|
||||
go.etcd.io/bbolt v1.5.0
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0
|
||||
go.opentelemetry.io/contrib/zpages v0.70.0
|
||||
go.opentelemetry.io/otel v1.45.0
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0
|
||||
go.opentelemetry.io/contrib/zpages v0.71.0
|
||||
go.opentelemetry.io/otel v1.46.0
|
||||
go.opentelemetry.io/otel/exporters/jaeger v1.17.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0
|
||||
go.opentelemetry.io/otel/sdk v1.45.0
|
||||
go.opentelemetry.io/otel/trace v1.45.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0
|
||||
go.opentelemetry.io/otel/sdk v1.46.0
|
||||
go.opentelemetry.io/otel/trace v1.46.0
|
||||
golang.org/x/crypto v0.55.0
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
|
||||
golang.org/x/image v0.45.0
|
||||
@@ -105,8 +105,8 @@ require (
|
||||
golang.org/x/sync v0.22.0
|
||||
golang.org/x/term v0.45.0
|
||||
golang.org/x/text v0.41.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d
|
||||
google.golang.org/grpc v1.83.1
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688
|
||||
google.golang.org/grpc v1.83.2
|
||||
google.golang.org/protobuf v1.36.12
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
gotest.tools/v3 v3.5.2
|
||||
@@ -135,13 +135,13 @@ require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bitly/go-simplejson v0.5.0 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.24.2 // indirect
|
||||
github.com/blevesearch/bleve_index_api v1.3.11 // indirect
|
||||
github.com/blevesearch/geo v0.2.5 // indirect
|
||||
github.com/blevesearch/go-faiss v1.1.0 // indirect
|
||||
github.com/blevesearch/bleve_index_api v1.4.1 // indirect
|
||||
github.com/blevesearch/geo v0.2.6 // indirect
|
||||
github.com/blevesearch/go-faiss v1.1.5 // indirect
|
||||
github.com/blevesearch/go-porterstemmer v1.0.3 // indirect
|
||||
github.com/blevesearch/gtreap v0.1.1 // indirect
|
||||
github.com/blevesearch/mmap-go v1.2.0 // indirect
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.4.7 // indirect
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.4.10 // indirect
|
||||
github.com/blevesearch/segment v0.9.1 // indirect
|
||||
github.com/blevesearch/snowballstem v0.9.0 // indirect
|
||||
github.com/blevesearch/upsidedown_store_api v1.0.2 // indirect
|
||||
@@ -152,7 +152,7 @@ require (
|
||||
github.com/blevesearch/zapx/v14 v14.4.3 // indirect
|
||||
github.com/blevesearch/zapx/v15 v15.4.3 // indirect
|
||||
github.com/blevesearch/zapx/v16 v16.3.4 // indirect
|
||||
github.com/blevesearch/zapx/v17 v17.1.2 // indirect
|
||||
github.com/blevesearch/zapx/v17 v17.2.3 // indirect
|
||||
github.com/bluele/gcache v0.0.2 // indirect
|
||||
github.com/bombsimon/logrusr/v3 v3.1.0 // indirect
|
||||
github.com/ceph/go-ceph v0.40.0 // indirect
|
||||
@@ -168,7 +168,6 @@ require (
|
||||
github.com/crewjam/httperr v0.2.0 // indirect
|
||||
github.com/crewjam/saml v0.4.14 // indirect
|
||||
github.com/cyphar/filepath-securejoin v0.6.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/deckarep/golang-set v1.8.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect
|
||||
github.com/desertbit/timer v1.0.1 // indirect
|
||||
@@ -290,7 +289,6 @@ require (
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.26 // indirect
|
||||
github.com/pjbgf/sha1cd v0.6.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/pquerna/cachecontrol v0.2.0 // indirect
|
||||
github.com/prometheus/alertmanager v0.33.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
@@ -333,8 +331,8 @@ require (
|
||||
go.etcd.io/etcd/client/v3 v3.7.1 // indirect
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.45.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.46.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.1 // indirect
|
||||
@@ -345,12 +343,11 @@ require (
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.49.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.3 // indirect
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
|
||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
sigs.k8s.io/yaml v1.6.0 // indirect
|
||||
)
|
||||
|
||||
|
||||
@@ -104,8 +104,8 @@ github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/bbalet/stopwords v1.0.0 h1:0TnGycCtY0zZi4ltKoOGRFIlZHv0WqpoIGUsObjztfo=
|
||||
github.com/bbalet/stopwords v1.0.0/go.mod h1:sAWrQoDMfqARGIn4s6dp7OW7ISrshUD8IP2q3KoqPjc=
|
||||
github.com/beevik/etree v1.7.0 h1:xjBk9O4p4x7D1YajePjfLzdaFC4/uYUENA7P0pv6gXA=
|
||||
github.com/beevik/etree v1.7.0/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc=
|
||||
github.com/beevik/etree v1.7.1 h1:xBlSFAjlMfZkrCNKCEdZ2MSN9pfQYeRBaISDnAVi4Ek=
|
||||
github.com/beevik/etree v1.7.1/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc=
|
||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||
@@ -116,22 +116,22 @@ github.com/bitly/go-simplejson v0.5.0 h1:6IH+V8/tVMab511d5bn4M7EwGXZf9Hj6i2xSwkN
|
||||
github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA=
|
||||
github.com/bits-and-blooms/bitset v1.24.2 h1:M7/NzVbsytmtfHbumG+K2bremQPMJuqv1JD3vOaFxp0=
|
||||
github.com/bits-and-blooms/bitset v1.24.2/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/blevesearch/bleve/v2 v2.6.0 h1:Cyd3dd4q5tCbOV8MnKUVRUDYMHOir9xn12NZzXVSEd4=
|
||||
github.com/blevesearch/bleve/v2 v2.6.0/go.mod h1:gLmI8lWgHgrIYf7UpUX7JISI1CaqC6VScu46mHThuAY=
|
||||
github.com/blevesearch/bleve_index_api v1.3.11 h1:x29vbV8OjWfLcrDVd7Lr1q+BkLNS0JWNEig0MCVnKH4=
|
||||
github.com/blevesearch/bleve_index_api v1.3.11/go.mod h1:xvd48t5XMeeioWQ5/jZvgLrV98flT2rdvEJ3l/ki4Ko=
|
||||
github.com/blevesearch/geo v0.2.5 h1:yJg9FX1oRwLnjXSXF+ECHfXFTF4diF02Ca/qUGVjJhE=
|
||||
github.com/blevesearch/geo v0.2.5/go.mod h1:Jhq7WE2K6mJTx1xS44M2pUO6Io+wjCSHh1+co3YOgH4=
|
||||
github.com/blevesearch/go-faiss v1.1.0 h1:xM7Jc0ZUCv5lssG9Ohj3Jv0SdTpxcUABU1dDt9XVsc4=
|
||||
github.com/blevesearch/go-faiss v1.1.0/go.mod h1:OMGQwOaRRYxrmeNdMrXJPvVx8gBnvE5RYrr0BahNnkk=
|
||||
github.com/blevesearch/bleve/v2 v2.6.1 h1:47vLskRTqxvQEtxVPYHjf5KpOgzD2msslXFjvUQCgWQ=
|
||||
github.com/blevesearch/bleve/v2 v2.6.1/go.mod h1:Dvvx6ZoEBTOj6RSzfk0lEz0wce/qhe2yOUubXeuzd2c=
|
||||
github.com/blevesearch/bleve_index_api v1.4.1 h1:CYIyecFlI+/RYjzUm+NmDjYbSvk870Bb7f+Vl4b12q8=
|
||||
github.com/blevesearch/bleve_index_api v1.4.1/go.mod h1:xvd48t5XMeeioWQ5/jZvgLrV98flT2rdvEJ3l/ki4Ko=
|
||||
github.com/blevesearch/geo v0.2.6 h1:7K1oyQKYlauC+mJuo2AfNPyjN/4mihEoJMfyClVH1Mo=
|
||||
github.com/blevesearch/geo v0.2.6/go.mod h1:6qzVUiB4BK47QkSZcRqiXEP2W3EeXuzM5XFTF8AdZ8A=
|
||||
github.com/blevesearch/go-faiss v1.1.5 h1:/IU5lkOahH9Ghfk9n3F6N0XD7PYVXZJWmNDc9TtXuco=
|
||||
github.com/blevesearch/go-faiss v1.1.5/go.mod h1:w3W9AiWsFRGVaMG+/cmJi7iHEAuGyC6blsgO1EzCK/M=
|
||||
github.com/blevesearch/go-porterstemmer v1.0.3 h1:GtmsqID0aZdCSNiY8SkuPJ12pD4jI+DdXTAn4YRcHCo=
|
||||
github.com/blevesearch/go-porterstemmer v1.0.3/go.mod h1:angGc5Ht+k2xhJdZi511LtmxuEf0OVpvUUNrwmM1P7M=
|
||||
github.com/blevesearch/gtreap v0.1.1 h1:2JWigFrzDMR+42WGIN/V2p0cUvn4UP3C4Q5nmaZGW8Y=
|
||||
github.com/blevesearch/gtreap v0.1.1/go.mod h1:QaQyDRAT51sotthUWAH4Sj08awFSSWzgYICSZ3w0tYk=
|
||||
github.com/blevesearch/mmap-go v1.2.0 h1:l33nNKPFcBjJUMwem6sAYJPUzhUCABoK9FxZDGiFNBI=
|
||||
github.com/blevesearch/mmap-go v1.2.0/go.mod h1:Vd6+20GBhEdwJnU1Xohgt88XCD/CTWcqbCNxkZpyBo0=
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.4.7 h1:GlMzW08hcsM3DnLUxhyF/1PcDal1qtvvIuytuph5djw=
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.4.7/go.mod h1://IJ7tG3QCf0cWW/aVSXqy77tc1AvLu3fcJLYEvOAFs=
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.4.10 h1:C3873+iWZ0YJM2ijaSHhJJzSvD4x1k+5UaQdGygZVhM=
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.4.10/go.mod h1:WUUkAocbkDlNK/kgAE13NvS9oxe+u618mYZ8sOvcCc4=
|
||||
github.com/blevesearch/segment v0.9.1 h1:+dThDy+Lvgj5JMxhmOVlgFfkUtZV2kw49xax4+jTfSU=
|
||||
github.com/blevesearch/segment v0.9.1/go.mod h1:zN21iLm7+GnBHWTao9I+Au/7MBiL8pPFtJBJTsk6kQw=
|
||||
github.com/blevesearch/snowballstem v0.9.0 h1:lMQ189YspGP6sXvZQ4WZ+MLawfV8wOmPoD/iWeNXm8s=
|
||||
@@ -152,8 +152,8 @@ github.com/blevesearch/zapx/v15 v15.4.3 h1:iJiMJOHrz216jyO6lS0m9RTCEkprUnzvqAI2l
|
||||
github.com/blevesearch/zapx/v15 v15.4.3/go.mod h1:1pssev/59FsuWcgSnTa0OeEpOzmhtmr/0/11H0Z8+Nw=
|
||||
github.com/blevesearch/zapx/v16 v16.3.4 h1:hDAqA8qusZTNbPEL7//w5P65UZ2de6yhSeUaTbp0Po0=
|
||||
github.com/blevesearch/zapx/v16 v16.3.4/go.mod h1:zqkPPqs9GS9FzVWzCO3Wf1X044yWAV17+4zb+FTiEHg=
|
||||
github.com/blevesearch/zapx/v17 v17.1.2 h1:avbOk2igaASNoiy0BE/jPgcxAnRI2PGeydeP4hg7Ikk=
|
||||
github.com/blevesearch/zapx/v17 v17.1.2/go.mod h1:WQObxKrqUX7cd0G1GMvDfc/bmZzQvoy7APOPimx7DiI=
|
||||
github.com/blevesearch/zapx/v17 v17.2.3 h1:UYYJPAt5b2tVxldx5h0jmv23RMsg8/UZKFVya7v92po=
|
||||
github.com/blevesearch/zapx/v17 v17.2.3/go.mod h1:r7mb4QWbDQSkbAnOjCb9iCfkcrzajB4yBdJpuBIo/fE=
|
||||
github.com/bluele/gcache v0.0.2 h1:WcbfdXICg7G/DGBh1PFfcirkWOQV+v077yF1pSy3DGw=
|
||||
github.com/bluele/gcache v0.0.2/go.mod h1:m15KV+ECjptwSPxKhOhQoAFQVtUFjTVkc3H8o0t/fp0=
|
||||
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
|
||||
@@ -286,8 +286,8 @@ github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkPro
|
||||
github.com/go-asn1-ber/asn1-ber v1.4.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
|
||||
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
|
||||
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-chi/httprate v0.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
|
||||
github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
|
||||
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
|
||||
@@ -725,8 +725,8 @@ github.com/onsi/ginkgo/v2 v2.32.1 h1:6tlvcDm/3sE8lGJbZ4+d4mO3RLy24/tQWOFzVSQNIfw
|
||||
github.com/onsi/ginkgo/v2 v2.32.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44=
|
||||
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
||||
github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I=
|
||||
github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
|
||||
github.com/onsi/gomega v1.43.0 h1:VlG/1FxqNxhSO+lq/OHBNaaqwiBK/mO8JbVkX9Y+FeU=
|
||||
github.com/onsi/gomega v1.43.0/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
|
||||
github.com/open-policy-agent/opa v1.19.0 h1:+j2OCsjMezZEML2T1lI9giJdGJS/PL1XFKgkHPGIhpo=
|
||||
github.com/open-policy-agent/opa v1.19.0/go.mod h1:pb6Y6klyf7X7X8uXNDflruA9dQC2gMqWROXI5w/kvv0=
|
||||
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
|
||||
@@ -846,8 +846,8 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/sirupsen/logrus v1.10.0 h1:T8MxJJXVZkfcC5zSRMRAg2F8+lxjmUCGGWPzFxO+Msc=
|
||||
github.com/sirupsen/logrus v1.10.0/go.mod h1:FXZFonkDAnFozmO+5hGAFvB0Yg9/j2SIhA/QuIkP180=
|
||||
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
|
||||
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
|
||||
github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=
|
||||
github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=
|
||||
github.com/spacewander/go-suffix-tree v0.0.0-20191010040751-0865e368c784 h1:0jjO3HdJfOn6gYHD/ZNZh0LLMxEAqkYX7xoDPQReEgs=
|
||||
@@ -877,8 +877,9 @@ github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1F
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/stvp/go-udp-testing v0.0.0-20201019212854-469649b16807/go.mod h1:7jxmlfBCDBXRzr0eAQJ48XC1hBu1np4CS5+cHEYfwpc=
|
||||
github.com/tchap/go-patricia/v2 v2.3.3 h1:xfNEsODumaEcCcY3gI0hYPZ/PcpVv5ju6RMAhgwZDDc=
|
||||
github.com/tchap/go-patricia/v2 v2.3.3/go.mod h1:VZRHKAb53DLaG+nA9EaYYiaEx6YztwDlLElMsnSHD4k=
|
||||
@@ -965,28 +966,28 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
|
||||
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 h1:oECp5f+hN7nkwjU/8BxQ/q23bGPb8FIrD839owX222E=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0/go.mod h1:DqEFwLumhzMBDQv9PcWbyoDxHI/4lAk6CM4nJBH39sc=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04=
|
||||
go.opentelemetry.io/contrib/zpages v0.70.0 h1:uBcclHekIrCRLO4KZfXiebDcWB52QQXaHGgvhUJ1K5I=
|
||||
go.opentelemetry.io/contrib/zpages v0.70.0/go.mod h1:Nz9A1+68HVoJrk+cg92zJbcbHFAa+Jbl1uINwAlcK94=
|
||||
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
|
||||
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 h1:B2h3uqicet1CT2N5TOFhS+Gq++9i0/CLmaxvhmhtP5s=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0/go.mod h1:dylvB+ZiiwMvsDij9O84Uy7SijLgHMX4mbkncds+4Sw=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/contrib/zpages v0.71.0 h1:OrQSEmdlfknIusEyGj/t30uBR7MnbmGcCRBt5ov8/rA=
|
||||
go.opentelemetry.io/contrib/zpages v0.71.0/go.mod h1:C3IIpqkQbjswcSREqxQLyEapF0SI9bqwJpxpjwtzFrE=
|
||||
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
|
||||
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
|
||||
go.opentelemetry.io/otel/exporters/jaeger v1.17.0 h1:D7UpUy2Xc2wsi1Ras6V40q806WM07rqoCWzXu7Sqy+4=
|
||||
go.opentelemetry.io/otel/exporters/jaeger v1.17.0/go.mod h1:nPCqOnEH9rNLKqH/+rrUjiMzHJdV1BlpKcTwRTyKkKI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI=
|
||||
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
|
||||
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
|
||||
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
|
||||
go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
|
||||
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
|
||||
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0 h1:w53CDeOA/Kurp7yRsegSr6pbbr759dOvJ+yNmWM6Hxs=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0/go.mod h1:BOmGMCbAtvcJiSJ+hLuhgPLdDbimnraSl8irz3iY8sY=
|
||||
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
|
||||
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
|
||||
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
|
||||
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
@@ -1326,10 +1327,10 @@ google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6D
|
||||
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688 h1:ax2KzoSRIZU/M0cIxri3pKxy99vniH1PVxWC6si/eZI=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688/go.mod h1:1RJ9BQGyNdZwkGc1eTqkErfRZ6RJyYPHZo73BZ1vQqI=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
||||
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
@@ -1343,8 +1344,8 @@ google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3Iji
|
||||
google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
|
||||
google.golang.org/grpc v1.83.1 h1:HIO0+BEtBP6soyqvqC8sNUjZ7bTs+0hFQuFF+RAy++Y=
|
||||
google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/grpc/examples v0.0.0-20211102180624-670c133e568e h1:m7aQHHqd0q89mRwhwS9Bx2rjyl/hsFAeta+uGrHsQaU=
|
||||
google.golang.org/grpc/examples v0.0.0-20211102180624-670c133e568e/go.mod h1:gID3PKrg7pWKntu9Ss6zTLJ0ttC0X9IHgREOCZwbCVU=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
|
||||
+6
-1
@@ -1,8 +1,13 @@
|
||||
Release 1.7.0
|
||||
Release 1.7.1
|
||||
=============
|
||||
|
||||
**Changes**
|
||||
|
||||
* Improve efficiency of `Element.Text` and `Element.Tail`.
|
||||
|
||||
Release 1.7.0
|
||||
=============
|
||||
|
||||
**Breaking changes**
|
||||
|
||||
* To address a security issue, it was necessary to add a `MaxDepth` option to
|
||||
|
||||
+20
-4
@@ -635,13 +635,17 @@ func (e *Element) Text() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
text := ""
|
||||
var text string
|
||||
var b strings.Builder
|
||||
for _, ch := range e.Child {
|
||||
if cd, ok := ch.(*CharData); ok {
|
||||
if text == "" {
|
||||
text = cd.Data
|
||||
} else {
|
||||
text += cd.Data
|
||||
if b.Len() == 0 {
|
||||
b.WriteString(text)
|
||||
}
|
||||
b.WriteString(cd.Data)
|
||||
}
|
||||
} else if _, ok := ch.(*Comment); ok {
|
||||
// ignore
|
||||
@@ -649,6 +653,10 @@ func (e *Element) Text() string {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if b.Len() > 0 {
|
||||
return b.String()
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
@@ -674,18 +682,26 @@ func (e *Element) Tail() string {
|
||||
p := e.Parent()
|
||||
i := e.Index()
|
||||
|
||||
text := ""
|
||||
var text string
|
||||
var b strings.Builder
|
||||
for _, ch := range p.Child[i+1:] {
|
||||
if cd, ok := ch.(*CharData); ok {
|
||||
if text == "" {
|
||||
text = cd.Data
|
||||
} else {
|
||||
text += cd.Data
|
||||
if b.Len() == 0 {
|
||||
b.WriteString(text)
|
||||
}
|
||||
b.WriteString(cd.Data)
|
||||
}
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if b.Len() > 0 {
|
||||
return b.String()
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package document
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/geo"
|
||||
"github.com/blevesearch/bleve/v2/geov2"
|
||||
"github.com/blevesearch/bleve/v2/size"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/geojson"
|
||||
)
|
||||
|
||||
var reflectStaticSizeGeoShapeV2Field int
|
||||
|
||||
func init() {
|
||||
var f GeoShapeV2Field
|
||||
reflectStaticSizeGeoShapeV2Field = int(reflect.TypeOf(f).Size())
|
||||
}
|
||||
|
||||
type GeoShapeV2Field struct {
|
||||
name string
|
||||
|
||||
shape index.GeoJSON
|
||||
inner []uint64
|
||||
cross []uint64
|
||||
scoreInner uint64
|
||||
scoreCross uint64
|
||||
bBoxBytes []byte
|
||||
shapeBytes []byte
|
||||
|
||||
options index.FieldIndexingOptions
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) Name() string {
|
||||
return f.name
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) ArrayPositions() []uint64 {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) Options() index.FieldIndexingOptions {
|
||||
return f.options
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) Analyze() {
|
||||
f.inner, f.cross = f.shape.IndexCells()
|
||||
f.scoreInner = geov2.CalcCellsScore(f.inner)
|
||||
f.scoreCross = geov2.CalcCellsScore(f.cross)
|
||||
|
||||
if bBox, ok := f.shape.BoundingBox().(*geojson.Envelope); ok {
|
||||
bBoxBytes, err := bBox.Marshal()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
f.bBoxBytes = bBoxBytes
|
||||
}
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) Value() []byte {
|
||||
return []byte{}
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) NumPlainTextBytes() uint64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) Size() int {
|
||||
return reflectStaticSizeGeoShapeV2Field + size.SizeOfPtr +
|
||||
len(f.name) +
|
||||
len(f.inner)*size.SizeOfUint64 +
|
||||
len(f.cross)*size.SizeOfUint64 +
|
||||
len(f.bBoxBytes) +
|
||||
len(f.shapeBytes)
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) EncodedFieldType() byte {
|
||||
return 'o'
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) AnalyzedLength() int {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) AnalyzedTokenFrequencies() index.TokenFrequencies {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) InnerCells() []uint64 {
|
||||
return f.inner
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) CrossCells() []uint64 {
|
||||
return f.cross
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) EncodedBoundingBox() []byte {
|
||||
return f.bBoxBytes
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) EncodedShape() []byte {
|
||||
return f.shapeBytes
|
||||
}
|
||||
|
||||
func (f *GeoShapeV2Field) Scores() (uint64, uint64) {
|
||||
return f.scoreInner, f.scoreCross
|
||||
}
|
||||
|
||||
func NewGeoShapeV2FieldFromShapeWithIndexingOptions(name string, geoShape *geojson.GeoShape,
|
||||
options index.FieldIndexingOptions) *GeoShapeV2Field {
|
||||
|
||||
var shape index.GeoJSON
|
||||
var shapeBytes []byte
|
||||
var err error
|
||||
|
||||
if geoShape.Type == geo.CircleType {
|
||||
shape, shapeBytes, err = geo.NewGeoCircleShape(geoShape.Center,
|
||||
geoShape.Radius)
|
||||
} else {
|
||||
shape, shapeBytes, err = geo.NewGeoJsonShape(geoShape.Coordinates,
|
||||
geoShape.Type)
|
||||
}
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &GeoShapeV2Field{
|
||||
name: name,
|
||||
shape: shape,
|
||||
options: options,
|
||||
shapeBytes: shapeBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func NewGeometryCollectionV2FieldFromShapesWithIndexingOptions(name string,
|
||||
geoShapes []*geojson.GeoShape, options index.FieldIndexingOptions) *GeoShapeV2Field {
|
||||
shape, shapeBytes, err := geo.NewGeometryCollectionFromShapes(geoShapes)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &GeoShapeV2Field{
|
||||
name: name,
|
||||
shape: shape,
|
||||
options: options,
|
||||
shapeBytes: shapeBytes,
|
||||
}
|
||||
}
|
||||
+60
@@ -246,6 +246,21 @@ func (p *Point) QueryTokens(s *S2SpatialAnalyzerPlugin) []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Point) IndexCells() ([]uint64, []uint64) {
|
||||
// placeholder implementation
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (p *Point) QueryCells() ([]uint64, []uint64) {
|
||||
// placeholder implementation
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (p *Point) BoundingBox() index.GeoJSON {
|
||||
// placeholder implementation
|
||||
return nil
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------------------------
|
||||
|
||||
type boundedRectangle struct {
|
||||
@@ -293,6 +308,21 @@ func (br *boundedRectangle) QueryTokens(s *S2SpatialAnalyzerPlugin) []string {
|
||||
return geojson.StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
func (br *boundedRectangle) IndexCells() ([]uint64, []uint64) {
|
||||
// placeholder implementation
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (br *boundedRectangle) QueryCells() ([]uint64, []uint64) {
|
||||
// placeholder implementation
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (br *boundedRectangle) BoundingBox() index.GeoJSON {
|
||||
// placeholder implementation
|
||||
return nil
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------------------------
|
||||
|
||||
type boundedPolygon struct {
|
||||
@@ -341,6 +371,21 @@ func (bp *boundedPolygon) QueryTokens(s *S2SpatialAnalyzerPlugin) []string {
|
||||
return geojson.StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
func (bp *boundedPolygon) IndexCells() ([]uint64, []uint64) {
|
||||
// placeholder implementation
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (bp *boundedPolygon) QueryCells() ([]uint64, []uint64) {
|
||||
// placeholder implementation
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (bp *boundedPolygon) BoundingBox() index.GeoJSON {
|
||||
// placeholder implementation
|
||||
return nil
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------------------------
|
||||
|
||||
type pointDistance struct {
|
||||
@@ -389,6 +434,21 @@ func (pd *pointDistance) QueryTokens(s *S2SpatialAnalyzerPlugin) []string {
|
||||
return geojson.StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
func (pd *pointDistance) IndexCells() ([]uint64, []uint64) {
|
||||
// placeholder implementation
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (pd *pointDistance) QueryCells() ([]uint64, []uint64) {
|
||||
// placeholder implementation
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (pd *pointDistance) BoundingBox() index.GeoJSON {
|
||||
// placeholder implementation
|
||||
return nil
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
// NewGeometryCollection instantiate a geometrycollection
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geov2
|
||||
|
||||
import "github.com/blevesearch/geo/s2"
|
||||
|
||||
// getCellSearchBounds takes a raw uint64 S2 cell ID and returns the
|
||||
// minimum and maximum uint64 values defining its absolute spatial range.
|
||||
func getCellSearchBounds(cellUint uint64) (min uint64, max uint64) {
|
||||
cellID := s2.CellID(cellUint)
|
||||
|
||||
rangeMin := cellID.RangeMin()
|
||||
rangeMax := cellID.RangeMax()
|
||||
|
||||
return uint64(rangeMin), uint64(rangeMax)
|
||||
}
|
||||
|
||||
// Returns the level of the given S2 cell ID
|
||||
func getCellLevel(cell uint64) uint64 {
|
||||
return uint64(s2.CellID(cell).Level())
|
||||
}
|
||||
|
||||
// Returns the parent cell ID of the given S2 cell ID at the specified level
|
||||
func getParentCell(cell uint64, level int) uint64 {
|
||||
return uint64(s2.CellID(cell).Parent(level))
|
||||
}
|
||||
|
||||
// CalcCellsScore returns the total area of the given S2 cells
|
||||
// in level 16 cell units (maxCellLevel in the geo repo's region coverer
|
||||
// configuration - see geo/geojson/geojson_v2.go)
|
||||
func CalcCellsScore(cells []uint64) uint64 {
|
||||
var score uint64
|
||||
for _, cell := range cells {
|
||||
score += calcScore(0, getCellLevel(cell))
|
||||
}
|
||||
return score
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geov2
|
||||
|
||||
import segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
|
||||
type queryEvaluator struct {
|
||||
queryInnerCells []uint64
|
||||
queryCrossCells []uint64
|
||||
|
||||
innerCells []uint64
|
||||
innerDocIDs []uint32
|
||||
|
||||
crossCells []uint64
|
||||
crossDocIDs []uint32
|
||||
}
|
||||
|
||||
func NewQueryEvaluator(query Query, geoData segment.GeoShapeV2Data) *queryEvaluator {
|
||||
return &queryEvaluator{
|
||||
queryInnerCells: query.InnerCells(),
|
||||
queryCrossCells: query.CrossCells(),
|
||||
innerCells: geoData.InnerCells(),
|
||||
innerDocIDs: geoData.InnerDocIDs(),
|
||||
crossCells: geoData.CrossCells(),
|
||||
crossDocIDs: geoData.CrossDocIDs(),
|
||||
}
|
||||
}
|
||||
|
||||
// find the leftmost index in arr where arr[i] >= target, or
|
||||
// len(arr) if no such index exists
|
||||
func binarySearchLeftmostGreaterOrEqual(arr []uint64, target uint64) int {
|
||||
lo, hi := 0, len(arr)
|
||||
for lo < hi {
|
||||
mid := int(uint(lo+hi) >> 1) // bitshift avoids the addition overflow risk
|
||||
if arr[mid] < target {
|
||||
lo = mid + 1
|
||||
} else {
|
||||
hi = mid
|
||||
}
|
||||
}
|
||||
return lo
|
||||
}
|
||||
|
||||
// forEachScoredDoc invokes fn exactly once for every docID present in either
|
||||
// score map, passing that doc's inner and cross scores (0 when the doc is
|
||||
// absent from the corresponding map).
|
||||
func forEachScoredDoc(innerScores, crossScores map[uint32]uint64,
|
||||
fn func(id uint32, inner, cross uint64)) {
|
||||
for id, inner := range innerScores {
|
||||
fn(id, inner, crossScores[id])
|
||||
}
|
||||
for id, cross := range crossScores {
|
||||
if _, ok := innerScores[id]; !ok {
|
||||
fn(id, 0, cross)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// scan and score the overlap of query inner cells with all index cells
|
||||
func (qe *queryEvaluator) rangeScanInner(innerScores, crossScores map[uint32]uint64) {
|
||||
for _, cell := range qe.queryInnerCells {
|
||||
minVal, maxVal := getCellSearchBounds(cell)
|
||||
cellLevel := getCellLevel(cell)
|
||||
rangeScanOne(cell, minVal, maxVal, cellLevel, qe.innerCells, qe.innerDocIDs, innerScores)
|
||||
rangeScanOne(cell, minVal, maxVal, cellLevel, qe.crossCells, qe.crossDocIDs, crossScores)
|
||||
}
|
||||
}
|
||||
|
||||
// scan and score the overlap of query cross cells with all index cells
|
||||
func (qe *queryEvaluator) rangeScanCross(innerScores, crossScores map[uint32]uint64) {
|
||||
for _, cell := range qe.queryCrossCells {
|
||||
minVal, maxVal := getCellSearchBounds(cell)
|
||||
cellLevel := getCellLevel(cell)
|
||||
rangeScanOne(cell, minVal, maxVal, cellLevel, qe.innerCells, qe.innerDocIDs, innerScores)
|
||||
rangeScanOne(cell, minVal, maxVal, cellLevel, qe.crossCells, qe.crossDocIDs, crossScores)
|
||||
}
|
||||
}
|
||||
|
||||
// scan and score the overlap of a single query cell with the given index cells
|
||||
func rangeScanOne(queryCell uint64, minVal, maxVal, cellLevel uint64,
|
||||
indexCells []uint64, docIds []uint32, scores map[uint32]uint64) {
|
||||
// find the range of index cells within the min/max bounds of the query cell
|
||||
// end will be < start if there are no index cells within the bounds
|
||||
start := binarySearchLeftmostGreaterOrEqual(indexCells, minVal)
|
||||
end := binarySearchLeftmostGreaterOrEqual(indexCells, maxVal+1) - 1
|
||||
|
||||
// score all index cells within the bounds of the query cell
|
||||
for i := start; i <= end; i++ {
|
||||
id := docIds[i]
|
||||
val := indexCells[i]
|
||||
|
||||
valLevel := getCellLevel(val)
|
||||
scores[id] += calcScore(cellLevel, valLevel)
|
||||
}
|
||||
|
||||
// score all parent cells of the query cell that are present in the index
|
||||
// since parent cells are not within the min/max bounds
|
||||
for level := int(cellLevel) - 1; level >= 0; level-- {
|
||||
// get the parent cell of the query cell at this level
|
||||
parentCell := getParentCell(queryCell, level)
|
||||
// search for the leftmost index of this parent cell in the index cells
|
||||
parentStart := binarySearchLeftmostGreaterOrEqual(indexCells, parentCell)
|
||||
|
||||
// score all index cells that match this parent cell exactly
|
||||
for i := parentStart; i < len(indexCells) && indexCells[i] == parentCell; i++ {
|
||||
id := docIds[i]
|
||||
scores[id] += calcScore(cellLevel, uint64(level))
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geov2
|
||||
|
||||
import (
|
||||
"github.com/blevesearch/bleve/v2/util"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
type Query interface {
|
||||
Evaluate(geoData segment.GeoShapeV2Data) *util.Bitset
|
||||
InnerCells() []uint64
|
||||
CrossCells() []uint64
|
||||
}
|
||||
|
||||
func NewQuery(shape index.GeoJSON, relation string) Query {
|
||||
switch relation {
|
||||
case "contains":
|
||||
return NewContainsQuery(shape)
|
||||
case "intersects":
|
||||
return NewIntersectsQuery(shape)
|
||||
case "within":
|
||||
return NewWithinQuery(shape)
|
||||
case "disjoint":
|
||||
return NewDisjointQuery(shape)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geov2
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/util"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/geojson"
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
type containsQuery struct {
|
||||
innerCells []uint64
|
||||
crossCells []uint64
|
||||
|
||||
shape index.GeoJSON
|
||||
bBox index.GeoJSON
|
||||
|
||||
score uint64
|
||||
}
|
||||
|
||||
func NewContainsQuery(shape index.GeoJSON) Query {
|
||||
inner, cross := shape.QueryCells()
|
||||
|
||||
score := CalcCellsScore(inner) + CalcCellsScore(cross)
|
||||
|
||||
return &containsQuery{
|
||||
innerCells: inner,
|
||||
crossCells: cross,
|
||||
shape: shape,
|
||||
bBox: shape.BoundingBox(),
|
||||
score: score,
|
||||
}
|
||||
}
|
||||
|
||||
func (cq *containsQuery) Evaluate(geoData segment.GeoShapeV2Data) *util.Bitset {
|
||||
numDocs := int(geoData.NumDocs())
|
||||
exclude := geoData.Excluded()
|
||||
|
||||
// create bitsets for hits and maybeHits providing exclude to the bitset
|
||||
// which will make it impossible to set those bits
|
||||
hits := util.NewBitset(numDocs, exclude)
|
||||
maybeHits := util.NewBitset(numDocs, exclude)
|
||||
|
||||
// failsafe for a degenerate query shape that produced no cells
|
||||
if cq.score == 0 {
|
||||
return hits
|
||||
}
|
||||
|
||||
// obtain zeroed score arrays from the segment-level pool and return
|
||||
// them once the evaluation is done
|
||||
innerScores := geoData.GetScoreMap()
|
||||
crossScores := geoData.GetScoreMap()
|
||||
defer geoData.PutScoreMap(innerScores)
|
||||
defer geoData.PutScoreMap(crossScores)
|
||||
|
||||
// create an evaluator instance to scan the query cells against the index cells
|
||||
evaluator := NewQueryEvaluator(cq, geoData)
|
||||
|
||||
// scan and score the overlap of all query cells with all index cells
|
||||
evaluator.rangeScanInner(innerScores, crossScores)
|
||||
evaluator.rangeScanCross(innerScores, crossScores)
|
||||
|
||||
// if all of the query cells are contained within the inner index cells
|
||||
// then we have a guaranteed hit, if they are contained within both the inner
|
||||
// and cross index cells then we have a maybe hit, otherwise we have no hit
|
||||
forEachScoredDoc(innerScores, crossScores, func(id uint32, inner, cross uint64) {
|
||||
docNum := int(id)
|
||||
if inner == cq.score {
|
||||
hits.Add(docNum)
|
||||
} else if inner+cross == cq.score {
|
||||
maybeHits.Add(docNum)
|
||||
}
|
||||
})
|
||||
|
||||
var reader *bytes.Reader
|
||||
|
||||
// filter out any maybeHits that do not have a bounding box that
|
||||
// contains the query bounding box
|
||||
boxFilter := func(docNum int) {
|
||||
docBBoxBytes, err := geoData.BoundingBox(uint32(docNum))
|
||||
if docBBoxBytes == nil || err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
docBBox, err := geojson.ExtractShapesFromBytes(docBBoxBytes, &reader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := docBBox.Contains(cq.bBox); err == nil && !ok {
|
||||
maybeHits.Remove(docNum)
|
||||
}
|
||||
}
|
||||
|
||||
maybeHits.Iterate(boxFilter)
|
||||
|
||||
// filter out any maybeHits that do not have a shape that
|
||||
// contains the query shape
|
||||
shapeFilter := func(docNum int) {
|
||||
docShapeBytes, err := geoData.Shape(uint32(docNum))
|
||||
if docShapeBytes == nil || err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
docShape, err := geojson.ExtractShapesFromBytes(docShapeBytes, &reader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := docShape.Contains(cq.shape); err == nil && ok {
|
||||
hits.Add(docNum)
|
||||
}
|
||||
}
|
||||
|
||||
maybeHits.Iterate(shapeFilter)
|
||||
|
||||
return hits
|
||||
}
|
||||
|
||||
func (cq *containsQuery) InnerCells() []uint64 {
|
||||
return cq.innerCells
|
||||
}
|
||||
|
||||
func (cq *containsQuery) CrossCells() []uint64 {
|
||||
return cq.crossCells
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geov2
|
||||
|
||||
import (
|
||||
"github.com/blevesearch/bleve/v2/util"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
type disjointQuery struct {
|
||||
innerCells []uint64
|
||||
crossCells []uint64
|
||||
|
||||
shape index.GeoJSON
|
||||
bBox index.GeoJSON
|
||||
}
|
||||
|
||||
func NewDisjointQuery(shape index.GeoJSON) Query {
|
||||
inner, cross := shape.QueryCells()
|
||||
|
||||
return &disjointQuery{
|
||||
innerCells: inner,
|
||||
crossCells: cross,
|
||||
shape: shape,
|
||||
bBox: shape.BoundingBox(),
|
||||
}
|
||||
}
|
||||
|
||||
func (dq *disjointQuery) Evaluate(geoData segment.GeoShapeV2Data) *util.Bitset {
|
||||
// evaluate the disjoint query by creating an intersects query and negating the results
|
||||
intersectsQuery := &intersectsQuery{
|
||||
innerCells: dq.innerCells,
|
||||
crossCells: dq.crossCells,
|
||||
shape: dq.shape,
|
||||
bBox: dq.bBox,
|
||||
}
|
||||
|
||||
// evaluate the intersects query to get the hits
|
||||
hits := intersectsQuery.Evaluate(geoData)
|
||||
|
||||
// invert the hits to get the disjoint results
|
||||
hits.Invert()
|
||||
|
||||
return hits
|
||||
}
|
||||
|
||||
func (dq *disjointQuery) InnerCells() []uint64 {
|
||||
return dq.innerCells
|
||||
}
|
||||
|
||||
func (dq *disjointQuery) CrossCells() []uint64 {
|
||||
return dq.crossCells
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geov2
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/util"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/geojson"
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
type intersectsQuery struct {
|
||||
innerCells []uint64
|
||||
crossCells []uint64
|
||||
|
||||
shape index.GeoJSON
|
||||
bBox index.GeoJSON
|
||||
}
|
||||
|
||||
func NewIntersectsQuery(shape index.GeoJSON) Query {
|
||||
inner, cross := shape.QueryCells()
|
||||
|
||||
return &intersectsQuery{
|
||||
innerCells: inner,
|
||||
crossCells: cross,
|
||||
shape: shape,
|
||||
bBox: shape.BoundingBox(),
|
||||
}
|
||||
}
|
||||
|
||||
func (iq *intersectsQuery) Evaluate(geoData segment.GeoShapeV2Data) *util.Bitset {
|
||||
numDocs := int(geoData.NumDocs())
|
||||
exclude := geoData.Excluded()
|
||||
|
||||
// create bitsets for hits and maybeHits providing exclude to the bitset
|
||||
// which will make it impossible to set those bits
|
||||
hits := util.NewBitset(numDocs, exclude)
|
||||
maybeHits := util.NewBitset(numDocs, exclude)
|
||||
|
||||
// obtain zeroed score arrays from the segment-level pool and return
|
||||
// them once the evaluation is done
|
||||
innerScores := geoData.GetScoreMap()
|
||||
crossScores := geoData.GetScoreMap()
|
||||
defer geoData.PutScoreMap(innerScores)
|
||||
defer geoData.PutScoreMap(crossScores)
|
||||
|
||||
// create an evaluator instance to scan the query cells against the index cells
|
||||
evaluator := NewQueryEvaluator(iq, geoData)
|
||||
|
||||
// scan and score the overlap of query inner cells with all index cells
|
||||
evaluator.rangeScanInner(innerScores, crossScores)
|
||||
|
||||
// if there is any overlap of query inner cells with any of the index cells
|
||||
// then we have a guaranteed hit. Reset scores to reuse score maps for the
|
||||
// next step
|
||||
forEachScoredDoc(innerScores, crossScores, func(id uint32, inner, cross uint64) {
|
||||
if inner > 0 || cross > 0 {
|
||||
hits.Add(int(id))
|
||||
}
|
||||
})
|
||||
clear(innerScores)
|
||||
clear(crossScores)
|
||||
|
||||
// scan and score the overlap of query cross cells with all index cells
|
||||
evaluator.rangeScanCross(innerScores, crossScores)
|
||||
|
||||
// if there is any overlap of query cross cells with any of the index inner
|
||||
// cells then we have a guaranteed hit, if there is any overlap of query cross
|
||||
// cells with any of the index cross cells then we have a maybe hit, otherwise
|
||||
// we have no hit.
|
||||
forEachScoredDoc(innerScores, crossScores, func(id uint32, inner, cross uint64) {
|
||||
docNum := int(id)
|
||||
if inner > 0 && !hits.Contains(docNum) {
|
||||
hits.Add(docNum)
|
||||
} else if cross > 0 && !hits.Contains(docNum) {
|
||||
maybeHits.Add(docNum)
|
||||
}
|
||||
})
|
||||
|
||||
var reader *bytes.Reader
|
||||
|
||||
// filter out any maybeHits that do not have a bounding box that
|
||||
// intersects the query bounding box
|
||||
boxFilter := func(docNum int) {
|
||||
docBBoxBytes, err := geoData.BoundingBox(uint32(docNum))
|
||||
if docBBoxBytes == nil || err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
docBBox, err := geojson.ExtractShapesFromBytes(docBBoxBytes, &reader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := docBBox.Intersects(iq.bBox); err == nil && !ok {
|
||||
maybeHits.Remove(docNum)
|
||||
}
|
||||
}
|
||||
|
||||
maybeHits.Iterate(boxFilter)
|
||||
|
||||
// filter out any maybeHits that do not have a shape that
|
||||
// intersects the query shape
|
||||
shapeFilter := func(docNum int) {
|
||||
docShapeBytes, err := geoData.Shape(uint32(docNum))
|
||||
if docShapeBytes == nil || err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
docShape, err := geojson.ExtractShapesFromBytes(docShapeBytes, &reader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := docShape.Intersects(iq.shape); err == nil && ok {
|
||||
hits.Add(docNum)
|
||||
}
|
||||
}
|
||||
|
||||
maybeHits.Iterate(shapeFilter)
|
||||
|
||||
return hits
|
||||
}
|
||||
|
||||
func (iq *intersectsQuery) InnerCells() []uint64 {
|
||||
return iq.innerCells
|
||||
}
|
||||
|
||||
func (iq *intersectsQuery) CrossCells() []uint64 {
|
||||
return iq.crossCells
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geov2
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/util"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/geojson"
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
type withinQuery struct {
|
||||
innerCells []uint64
|
||||
crossCells []uint64
|
||||
|
||||
shape index.GeoJSON
|
||||
bBox index.GeoJSON
|
||||
}
|
||||
|
||||
func NewWithinQuery(shape index.GeoJSON) Query {
|
||||
inner, cross := shape.QueryCells()
|
||||
|
||||
return &withinQuery{
|
||||
innerCells: inner,
|
||||
crossCells: cross,
|
||||
shape: shape,
|
||||
bBox: shape.BoundingBox(),
|
||||
}
|
||||
}
|
||||
|
||||
func (wq *withinQuery) Evaluate(geoData segment.GeoShapeV2Data) *util.Bitset {
|
||||
numDocs := int(geoData.NumDocs())
|
||||
exclude := geoData.Excluded()
|
||||
|
||||
// create bitsets for hits and maybeHits providing exclude to the bitset
|
||||
// which will make it impossible to set those bits
|
||||
hits := util.NewBitset(numDocs, exclude)
|
||||
maybeHits := util.NewBitset(numDocs, exclude)
|
||||
|
||||
// obtain zeroed score arrays from the segment-level pool and return
|
||||
// them once the evaluation is done
|
||||
innerScores := geoData.GetScoreMap()
|
||||
crossScores := geoData.GetScoreMap()
|
||||
defer geoData.PutScoreMap(innerScores)
|
||||
defer geoData.PutScoreMap(crossScores)
|
||||
|
||||
docScoresInner, docScoresCross := geoData.DocScores()
|
||||
|
||||
// create an evaluator instance to scan the query cells against the index cells
|
||||
evaluator := NewQueryEvaluator(wq, geoData)
|
||||
|
||||
// scan and score the overlap of query inner cells with all index cells
|
||||
evaluator.rangeScanInner(innerScores, crossScores)
|
||||
|
||||
// if all of the index cells are contained within the query inner cells,
|
||||
// then we have a guaranteed hit. Only consider documents with non zero
|
||||
// total scores as hits
|
||||
forEachScoredDoc(innerScores, crossScores, func(id uint32, inner, cross uint64) {
|
||||
total := inner + cross
|
||||
if total == docScoresInner[id]+docScoresCross[id] && total != 0 {
|
||||
hits.Add(int(id))
|
||||
}
|
||||
})
|
||||
|
||||
// scan and score the overlap of query cross cells with all index cells
|
||||
evaluator.rangeScanCross(innerScores, crossScores)
|
||||
|
||||
// A document is a maybe-hit once the accumulated score reaches at least
|
||||
// its own inner-cell score. Complete overlap of index and cross scores
|
||||
// may not always be possible due to the nature of region coverer being
|
||||
// non exhaustive in the sense that the boundaries are not always only
|
||||
// covered by the smallest possible cells.
|
||||
forEachScoredDoc(innerScores, crossScores, func(id uint32, inner, cross uint64) {
|
||||
docNum := int(id)
|
||||
total := inner + cross
|
||||
if !hits.Contains(docNum) && total >= docScoresInner[id] && total != 0 {
|
||||
maybeHits.Add(docNum)
|
||||
}
|
||||
})
|
||||
|
||||
var reader *bytes.Reader
|
||||
|
||||
// filter out any maybeHits that do not have a bounding box that
|
||||
// is within the query bounding box
|
||||
boxFilter := func(docNum int) {
|
||||
docBBoxBytes, err := geoData.BoundingBox(uint32(docNum))
|
||||
if docBBoxBytes == nil || err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
docBBox, err := geojson.ExtractShapesFromBytes(docBBoxBytes, &reader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := wq.bBox.Contains(docBBox); err == nil && !ok {
|
||||
maybeHits.Remove(docNum)
|
||||
}
|
||||
}
|
||||
|
||||
maybeHits.Iterate(boxFilter)
|
||||
|
||||
// filter out any maybeHits that do not have a shape that
|
||||
// is within the query shape
|
||||
shapeFilter := func(docNum int) {
|
||||
docShapeBytes, err := geoData.Shape(uint32(docNum))
|
||||
if docShapeBytes == nil || err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
docShape, err := geojson.ExtractShapesFromBytes(docShapeBytes, &reader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := wq.shape.Contains(docShape); err == nil && ok {
|
||||
hits.Add(docNum)
|
||||
}
|
||||
}
|
||||
|
||||
maybeHits.Iterate(shapeFilter)
|
||||
|
||||
return hits
|
||||
}
|
||||
|
||||
func (wq *withinQuery) InnerCells() []uint64 {
|
||||
return wq.innerCells
|
||||
}
|
||||
|
||||
func (wq *withinQuery) CrossCells() []uint64 {
|
||||
return wq.crossCells
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geov2
|
||||
|
||||
// pow4Table precomputes all valid powers of 4 for a uint64.
|
||||
// Array size 32 covers exp 0 through 31.
|
||||
var pow4Table = [32]uint64{
|
||||
1, // 4^0
|
||||
4, // 4^1
|
||||
16, // 4^2
|
||||
64, // 4^3
|
||||
256, // 4^4
|
||||
1024, // 4^5
|
||||
4096, // 4^6
|
||||
16384, // 4^7
|
||||
65536, // 4^8
|
||||
262144, // 4^9
|
||||
1048576, // 4^10
|
||||
4194304, // 4^11
|
||||
16777216, // 4^12
|
||||
67108864, // 4^13
|
||||
268435456, // 4^14
|
||||
1073741824, // 4^15
|
||||
4294967296, // 4^16
|
||||
17179869184, // 4^17
|
||||
68719476736, // 4^18
|
||||
274877906944, // 4^19
|
||||
1099511627776, // 4^20
|
||||
4398046511104, // 4^21
|
||||
17592186044416, // 4^22
|
||||
70368744177664, // 4^23
|
||||
281474976710656, // 4^24
|
||||
1125899906842624, // 4^25
|
||||
4503599627370496, // 4^26
|
||||
18014398509481984, // 4^27
|
||||
72057594037927936, // 4^28
|
||||
288230376151711744, // 4^29
|
||||
1152921504606846976, // 4^30
|
||||
4611686018427387904, // 4^31
|
||||
}
|
||||
|
||||
// pow4 returns 4^exp quickly using the lookup table.
|
||||
func pow4(exp uint64) uint64 {
|
||||
if exp >= 32 {
|
||||
// Handle overflow safely.
|
||||
return 0
|
||||
}
|
||||
return pow4Table[exp]
|
||||
}
|
||||
|
||||
// returns the overlap of query and index cells based on their levels.
|
||||
// Both levels are assumed to be at most 16 (maxCellLevel in the geo repo's
|
||||
// region coverer configuration - see geo/geojson/geojson_v2.go), the deepest
|
||||
// level used across the geoshape_v2 indexing and query cell coverings;
|
||||
// cells deeper than level 16 are outside this function's contract by design.
|
||||
func calcScore(queryCellLevel, indexCellLevel uint64) uint64 {
|
||||
if indexCellLevel > queryCellLevel {
|
||||
return pow4(16 - indexCellLevel)
|
||||
} else {
|
||||
return pow4(16 - queryCellLevel)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -303,7 +303,7 @@ func (o *Builder) Close() error {
|
||||
}
|
||||
|
||||
// fill the root bolt with this fake index snapshot
|
||||
_, _, err = prepareBoltSnapshot(is, tx, o.path, o.segPlugin, nil, nil)
|
||||
_, _, err = prepareBoltSnapshot(is, tx, o.path, o.segPlugin, nil)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
_ = rootBolt.Close()
|
||||
|
||||
+10
-1
@@ -14,7 +14,10 @@
|
||||
|
||||
package scorch
|
||||
|
||||
import segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
import (
|
||||
"github.com/RoaringBitmap/roaring/v2"
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
type emptyPostingsIterator struct{}
|
||||
|
||||
@@ -38,4 +41,10 @@ func (e *emptyPostingsIterator) ResetBytesRead(uint64) {}
|
||||
|
||||
func (e *emptyPostingsIterator) BytesWritten() uint64 { return 0 }
|
||||
|
||||
func (e *emptyPostingsIterator) ActualBitmap() *roaring.Bitmap { return nil }
|
||||
|
||||
func (e *emptyPostingsIterator) DocNum1Hit() (uint64, bool) { return 0, false }
|
||||
|
||||
func (e *emptyPostingsIterator) ReplaceActual(*roaring.Bitmap) {}
|
||||
|
||||
var anEmptyPostingsIterator = &emptyPostingsIterator{}
|
||||
+42
-38
@@ -32,7 +32,6 @@ type segmentIntroduction struct {
|
||||
obsoletes map[uint64]*roaring.Bitmap
|
||||
ids []string
|
||||
internal map[string][]byte
|
||||
stats *fieldStats
|
||||
|
||||
applied chan error
|
||||
persisted chan error
|
||||
@@ -154,7 +153,6 @@ func (s *Scorch) introduceSegment(next *segmentIntroduction) error {
|
||||
cachedDocs: root.segment[i].cachedDocs,
|
||||
cachedMeta: root.segment[i].cachedMeta,
|
||||
creator: root.segment[i].creator,
|
||||
internal: root.segment[i].internal,
|
||||
}
|
||||
|
||||
// apply new obsoletions
|
||||
@@ -197,13 +195,16 @@ func (s *Scorch) introduceSegment(next *segmentIntroduction) error {
|
||||
|
||||
// append new segment, if any, to end of the new index snapshot
|
||||
if next.data != nil {
|
||||
stats := newFieldStats()
|
||||
if fsr, ok := next.data.(segment.FieldStatsReporter); ok {
|
||||
fsr.UpdateFieldStats(stats)
|
||||
}
|
||||
newSegmentSnapshot := &SegmentSnapshot{
|
||||
id: next.id,
|
||||
segment: next.data, // take ownership of next.data's ref-count
|
||||
stats: next.stats,
|
||||
stats: stats,
|
||||
cachedDocs: &cachedDocs{cache: nil},
|
||||
cachedMeta: &cachedMeta{meta: nil},
|
||||
internal: make(map[string][]byte),
|
||||
cachedMeta: newCachedMeta(),
|
||||
creator: "introduceSegment",
|
||||
}
|
||||
newSnapshot.segment = append(newSnapshot.segment, newSegmentSnapshot)
|
||||
@@ -213,12 +214,6 @@ func (s *Scorch) introduceSegment(next *segmentIntroduction) error {
|
||||
// queued for persistence.
|
||||
atomic.AddUint64(&s.stats.TotIntroducedItems, newSegmentSnapshot.Count())
|
||||
atomic.AddUint64(&s.stats.TotIntroducedSegmentsBatch, 1)
|
||||
|
||||
// track the internal values of this segment so that when we update the
|
||||
// bolt we keep the internal values in sync with the segments on disk, and
|
||||
// if this segment didn't get persisted we need to undo that info from the
|
||||
// indexSnapshot's internal map as part of the bolt update.
|
||||
newSegmentSnapshot.internal = next.internal
|
||||
}
|
||||
// copy old values
|
||||
for key, oldVal := range root.internal {
|
||||
@@ -366,29 +361,29 @@ func (s *Scorch) introduceMerge(nextMerge *segmentMerge) {
|
||||
|
||||
var running, docsToPersistCount, memSegments, fileSegments uint64
|
||||
var droppedSegmentFiles []string
|
||||
newSegmentDeleted := make([]*roaring.Bitmap, len(nextMerge.new))
|
||||
for i := range newSegmentDeleted {
|
||||
newSegmentsDeleted := make([]*roaring.Bitmap, len(nextMerge.newSegments))
|
||||
for i := range newSegmentsDeleted {
|
||||
// create a bitmaps to track the obsoletes per newly merged segments
|
||||
newSegmentDeleted[i] = roaring.NewBitmap()
|
||||
newSegmentsDeleted[i] = roaring.NewBitmap()
|
||||
}
|
||||
|
||||
// iterate through current segments
|
||||
for i := range root.segment {
|
||||
segmentID := root.segment[i].id
|
||||
if segSnapAtMerge, ok := nextMerge.mergedSegHistory[segmentID]; ok {
|
||||
if history, ok := nextMerge.mergedSegHistory[segmentID]; ok {
|
||||
// this segment is going away, see if anything else was deleted since we started the merge
|
||||
if segSnapAtMerge != nil && root.segment[i].deleted != nil {
|
||||
if history != nil && root.segment[i].deleted != nil {
|
||||
// assume all these deletes are new
|
||||
deletedSince := root.segment[i].deleted
|
||||
// if we already knew about some of them, remove
|
||||
if segSnapAtMerge.oldSegment.deleted != nil {
|
||||
deletedSince = roaring.AndNot(root.segment[i].deleted, segSnapAtMerge.oldSegment.deleted)
|
||||
if history.oldSegment.deleted != nil {
|
||||
deletedSince = roaring.AndNot(root.segment[i].deleted, history.oldSegment.deleted)
|
||||
}
|
||||
deletedSinceItr := deletedSince.Iterator()
|
||||
for deletedSinceItr.HasNext() {
|
||||
oldDocNum := deletedSinceItr.Next()
|
||||
newDocNum := segSnapAtMerge.oldNewDocIDs[oldDocNum]
|
||||
newSegmentDeleted[segSnapAtMerge.workerID].Add(uint32(newDocNum))
|
||||
newDocNum := history.oldNewDocIDs[oldDocNum]
|
||||
newSegmentsDeleted[history.batchID].Add(uint32(newDocNum))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -407,7 +402,6 @@ func (s *Scorch) introduceMerge(nextMerge *segmentMerge) {
|
||||
cachedDocs: root.segment[i].cachedDocs,
|
||||
cachedMeta: root.segment[i].cachedMeta,
|
||||
creator: root.segment[i].creator,
|
||||
internal: root.segment[i].internal,
|
||||
})
|
||||
root.segment[i].segment.AddRef()
|
||||
newSnapshot.offsets = append(newSnapshot.offsets, running)
|
||||
@@ -436,18 +430,26 @@ func (s *Scorch) introduceMerge(nextMerge *segmentMerge) {
|
||||
for obsoletedIter.HasNext() {
|
||||
oldDocNum := obsoletedIter.Next()
|
||||
newDocNum := ss.oldNewDocIDs[oldDocNum]
|
||||
newSegmentDeleted[ss.workerID].Add(uint32(newDocNum))
|
||||
newSegmentsDeleted[ss.batchID].Add(uint32(newDocNum))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
skipped := true
|
||||
skipped := make([]bool, len(nextMerge.newSegments))
|
||||
// make the newly merged segments part of the newSnapshot being constructed
|
||||
for i, newMergedSegment := range nextMerge.new {
|
||||
for i, newMergedSegment := range nextMerge.newSegments {
|
||||
if newMergedSegment == nil {
|
||||
if nextMerge.fileMerge {
|
||||
atomic.AddUint64(&s.stats.TotFileMergeIntroductionsSkipped, 1)
|
||||
} else {
|
||||
atomic.AddUint64(&s.stats.TotMemMergeIntroductionsSkipped, 1)
|
||||
}
|
||||
skipped[i] = true
|
||||
continue
|
||||
}
|
||||
// checking if this newly merged segment is worth keeping based on
|
||||
// obsoleted doc count since the merge intro started
|
||||
if newMergedSegment != nil &&
|
||||
newMergedSegment.Count() > newSegmentDeleted[i].GetCardinality() {
|
||||
if newMergedSegment.Count() > newSegmentsDeleted[i].GetCardinality() {
|
||||
stats := newFieldStats()
|
||||
if fsr, ok := newMergedSegment.(segment.FieldStatsReporter); ok {
|
||||
fsr.UpdateFieldStats(stats)
|
||||
@@ -455,12 +457,12 @@ func (s *Scorch) introduceMerge(nextMerge *segmentMerge) {
|
||||
|
||||
// put the merged segment at the end of newSnapshot
|
||||
newSnapshot.segment = append(newSnapshot.segment, &SegmentSnapshot{
|
||||
id: nextMerge.id[i],
|
||||
segment: newMergedSegment, // take ownership for nextMerge.new's ref-count
|
||||
deleted: newSegmentDeleted[i],
|
||||
id: nextMerge.newSegmentIDs[i],
|
||||
segment: newMergedSegment, // take ownership for newMergedSegment's ref-count
|
||||
deleted: newSegmentsDeleted[i],
|
||||
stats: stats,
|
||||
cachedDocs: &cachedDocs{cache: nil},
|
||||
cachedMeta: &cachedMeta{meta: nil},
|
||||
cachedMeta: newCachedMeta(),
|
||||
creator: "introduceMerge",
|
||||
mmaped: nextMerge.mmaped,
|
||||
})
|
||||
@@ -471,19 +473,21 @@ func (s *Scorch) introduceMerge(nextMerge *segmentMerge) {
|
||||
case segment.PersistedSegment:
|
||||
fileSegments++
|
||||
default:
|
||||
docsToPersistCount += newMergedSegment.Count() - newSegmentDeleted[i].GetCardinality()
|
||||
docsToPersistCount += newMergedSegment.Count() - newSegmentsDeleted[i].GetCardinality()
|
||||
memSegments++
|
||||
}
|
||||
skipped = false
|
||||
atomic.AddUint64(&s.stats.TotIntroducedSegmentsMerge, 1)
|
||||
skipped[i] = false
|
||||
} else {
|
||||
if nextMerge.fileMerge {
|
||||
atomic.AddUint64(&s.stats.TotFileMergeIntroductionsObsoleted, 1)
|
||||
} else {
|
||||
atomic.AddUint64(&s.stats.TotMemMergeIntroductionsObsoleted, 1)
|
||||
}
|
||||
skipped[i] = true
|
||||
}
|
||||
}
|
||||
|
||||
if skipped {
|
||||
atomic.AddUint64(&s.stats.TotFileMergeIntroductionsObsoleted, 1)
|
||||
} else {
|
||||
atomic.AddUint64(&s.stats.TotIntroducedSegmentsMerge, uint64(len(nextMerge.new)))
|
||||
}
|
||||
|
||||
atomic.StoreUint64(&s.stats.TotItemsToPersist, docsToPersistCount)
|
||||
atomic.StoreUint64(&s.stats.TotMemorySegmentsAtRoot, memSegments)
|
||||
atomic.StoreUint64(&s.stats.TotFileSegmentsAtRoot, fileSegments)
|
||||
|
||||
+295
-246
@@ -16,6 +16,7 @@ package scorch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -59,17 +60,8 @@ func (s *Scorch) mergerLoop() {
|
||||
|
||||
var lastEpochMergePlanned uint64
|
||||
var ctrlMsg *mergerCtrl
|
||||
mergePlannerOptions, err := s.parseMergePlannerOptions()
|
||||
if err != nil {
|
||||
s.fireAsyncError(NewScorchError(
|
||||
merger,
|
||||
fmt.Sprintf("mergerPlannerOptions json parsing err: %v", err),
|
||||
ErrOptionsParse,
|
||||
))
|
||||
return
|
||||
}
|
||||
ctrlMsgDflt := &mergerCtrl{ctx: context.Background(),
|
||||
options: mergePlannerOptions,
|
||||
options: s.mergePlannerOptions,
|
||||
doneCh: nil}
|
||||
|
||||
OUTER:
|
||||
@@ -193,13 +185,13 @@ func (s *Scorch) ForceMerge(ctx context.Context,
|
||||
mo *mergeplan.MergePlanOptions) error {
|
||||
// check whether force merge is already under processing
|
||||
s.rootLock.Lock()
|
||||
if s.stats.TotFileMergeForceOpsStarted >
|
||||
s.stats.TotFileMergeForceOpsCompleted {
|
||||
if atomic.LoadUint64(&s.stats.TotFileMergeForceOpsStarted) >
|
||||
atomic.LoadUint64(&s.stats.TotFileMergeForceOpsCompleted) {
|
||||
s.rootLock.Unlock()
|
||||
return fmt.Errorf("force merge already in progress")
|
||||
}
|
||||
|
||||
s.stats.TotFileMergeForceOpsStarted++
|
||||
atomic.AddUint64(&s.stats.TotFileMergeForceOpsStarted, 1)
|
||||
s.rootLock.Unlock()
|
||||
|
||||
if mo != nil {
|
||||
@@ -233,14 +225,9 @@ func (s *Scorch) ForceMerge(ctx context.Context,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Scorch) parseMergePlannerOptions() (*mergeplan.MergePlanOptions,
|
||||
func (s *Scorch) parseMergePlannerOptions(po *persisterOptions) (*mergeplan.MergePlanOptions,
|
||||
error) {
|
||||
mergePlannerOptions := mergeplan.DefaultMergePlanOptions
|
||||
|
||||
po, err := s.parsePersisterOptions()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// by default use the MaxSizeInMemoryMergePerWorker from the persister option
|
||||
// as the FloorSegmentFileSize for the merge planner which would be the
|
||||
// first tier size in the planning. If the value is 0, then we don't use the
|
||||
@@ -297,6 +284,21 @@ func (w *closeChWrapper) listen() {
|
||||
}
|
||||
}
|
||||
|
||||
// mergeBatch represents a batch of segments to be merged together,
|
||||
// along with the new segment that will be created as a result of the merge.
|
||||
type mergeBatch struct {
|
||||
snapshots []*SegmentSnapshot
|
||||
filenames []string
|
||||
segments []segment.Segment
|
||||
drops []*roaring.Bitmap
|
||||
|
||||
new segment.Segment
|
||||
newID uint64
|
||||
newDocNums [][]uint64
|
||||
newFilename string
|
||||
newTime uint64
|
||||
}
|
||||
|
||||
// planMergeAtSnapshot plans and executes the merge operations for a given snapshot
|
||||
// if there is a custom merge plan function provided, it uses that to get the merge plan
|
||||
// otherwise, it builds the merge plan using the default planner and executes the merge tasks in the plan.
|
||||
@@ -313,7 +315,7 @@ func (s *Scorch) planMergeAtSnapshot(ctrlMsg *mergerCtrl, ourSnapshot *IndexSnap
|
||||
}
|
||||
|
||||
// default to making a merge plan if a custom one is not provided
|
||||
if mergePlan == nil {
|
||||
if mergePlan == nil || len(mergePlan.Tasks) == 0 {
|
||||
// build list of persisted segments in this snapshot
|
||||
var onlyPersistedSnapshots []mergeplan.Segment
|
||||
for _, segmentSnapshot := range ourSnapshot.segment {
|
||||
@@ -331,7 +333,8 @@ func (s *Scorch) planMergeAtSnapshot(ctrlMsg *mergerCtrl, ourSnapshot *IndexSnap
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanErr, 1)
|
||||
return fmt.Errorf("merge planning err: %v", err)
|
||||
}
|
||||
if mergePlan == nil {
|
||||
|
||||
if mergePlan == nil || len(mergePlan.Tasks) == 0 {
|
||||
// nothing to do
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanNone, 1)
|
||||
return nil
|
||||
@@ -345,7 +348,6 @@ func (s *Scorch) planMergeAtSnapshot(ctrlMsg *mergerCtrl, ourSnapshot *IndexSnap
|
||||
defer cw.close()
|
||||
go cw.listen()
|
||||
|
||||
var filenames []string
|
||||
var err error
|
||||
defer func() {
|
||||
// send error to done channel if present
|
||||
@@ -354,169 +356,190 @@ func (s *Scorch) planMergeAtSnapshot(ctrlMsg *mergerCtrl, ourSnapshot *IndexSnap
|
||||
}
|
||||
}()
|
||||
|
||||
for _, task := range mergePlan.Tasks {
|
||||
numBatches := len(mergePlan.Tasks)
|
||||
mergeBatches := make([]*mergeBatch, numBatches)
|
||||
defer func() {
|
||||
for batchID := 0; batchID < numBatches; batchID++ {
|
||||
batch := mergeBatches[batchID]
|
||||
if batch == nil {
|
||||
continue
|
||||
}
|
||||
if err == nil {
|
||||
s.rootLock.Lock()
|
||||
for _, filename := range batch.filenames {
|
||||
delete(s.ineligibleForRemoval, filename)
|
||||
}
|
||||
s.rootLock.Unlock()
|
||||
} else {
|
||||
if batch.new != nil {
|
||||
_ = batch.new.Close()
|
||||
}
|
||||
s.unmarkIneligibleForRemoval(batch.newFilename)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
numMergedSegments := 0
|
||||
for batchID := 0; batchID < numBatches; batchID++ {
|
||||
task := mergePlan.Tasks[batchID]
|
||||
if len(task.Segments) == 0 {
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanTasksSegmentsEmpty, 1)
|
||||
continue
|
||||
}
|
||||
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanTasksSegments, uint64(len(task.Segments)))
|
||||
|
||||
newSegmentID := atomic.AddUint64(&s.nextSegmentID, 1)
|
||||
segmentsToMerge := make([]segment.Segment, 0, len(task.Segments))
|
||||
docsToDrop := make([]*roaring.Bitmap, 0, len(task.Segments))
|
||||
mergedSegHistory := make(map[uint64]*mergedSegmentHistory, len(task.Segments))
|
||||
batch := &mergeBatch{
|
||||
snapshots: make([]*SegmentSnapshot, 0, len(task.Segments)),
|
||||
filenames: make([]string, 0, len(task.Segments)),
|
||||
segments: make([]segment.Segment, 0, len(task.Segments)),
|
||||
drops: make([]*roaring.Bitmap, 0, len(task.Segments)),
|
||||
|
||||
new: nil,
|
||||
newID: newSegmentID,
|
||||
newDocNums: nil,
|
||||
newFilename: zapFileName(newSegmentID),
|
||||
newTime: 0,
|
||||
}
|
||||
mergeBatches[batchID] = batch
|
||||
|
||||
for _, planSegment := range task.Segments {
|
||||
if segSnapshot, ok := planSegment.(*SegmentSnapshot); ok {
|
||||
mergedSegHistory[segSnapshot.id] = &mergedSegmentHistory{
|
||||
workerID: 0,
|
||||
oldSegment: segSnapshot,
|
||||
}
|
||||
if persistedSeg, ok := segSnapshot.segment.(segment.PersistedSegment); ok {
|
||||
if segSnapshot.LiveSize() == 0 {
|
||||
atomic.AddUint64(&s.stats.TotFileMergeSegmentsEmpty, 1)
|
||||
delete(mergedSegHistory, segSnapshot.id)
|
||||
} else {
|
||||
segmentsToMerge = append(segmentsToMerge, segSnapshot.segment)
|
||||
docsToDrop = append(docsToDrop, segSnapshot.deleted)
|
||||
batch.snapshots = append(batch.snapshots, segSnapshot)
|
||||
batch.segments = append(batch.segments, segSnapshot.segment)
|
||||
batch.drops = append(batch.drops, segSnapshot.deleted)
|
||||
}
|
||||
// track the files getting merged for unsetting the
|
||||
// removal ineligibility. This helps to unflip files
|
||||
// even with fast merger, slow persister work flows.
|
||||
path := persistedSeg.Path()
|
||||
filenames = append(filenames,
|
||||
batch.filenames = append(batch.filenames,
|
||||
strings.TrimPrefix(path, s.path+string(os.PathSeparator)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var seg segment.Segment
|
||||
var filename string
|
||||
if len(segmentsToMerge) > 0 {
|
||||
filename = zapFileName(newSegmentID)
|
||||
s.markIneligibleForRemoval(filename)
|
||||
path := s.path + string(os.PathSeparator) + filename
|
||||
|
||||
fileMergeZapStartTime := time.Now()
|
||||
|
||||
atomic.AddUint64(&s.stats.TotFileMergeZapBeg, 1)
|
||||
prevBytesReadTotal := cumulateBytesRead(segmentsToMerge)
|
||||
var newDocNums [][]uint64
|
||||
newDocNums, _, err = s.segPlugin.MergeUsing(segmentsToMerge, docsToDrop, path,
|
||||
cw.cancelCh, s, s.segmentConfig)
|
||||
atomic.AddUint64(&s.stats.TotFileMergeZapEnd, 1)
|
||||
|
||||
fileMergeZapTime := uint64(time.Since(fileMergeZapStartTime))
|
||||
atomic.AddUint64(&s.stats.TotFileMergeZapTime, fileMergeZapTime)
|
||||
if atomic.LoadUint64(&s.stats.MaxFileMergeZapTime) < fileMergeZapTime {
|
||||
atomic.StoreUint64(&s.stats.MaxFileMergeZapTime, fileMergeZapTime)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
s.unmarkIneligibleForRemoval(filename)
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanTasksErr, 1)
|
||||
if err == segment.ErrClosed {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("merging failed: %v", err)
|
||||
}
|
||||
|
||||
seg, err = s.segPlugin.OpenUsing(path, s.segmentConfig)
|
||||
if err != nil {
|
||||
s.unmarkIneligibleForRemoval(filename)
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanTasksErr, 1)
|
||||
return err
|
||||
}
|
||||
|
||||
totalBytesRead := seg.BytesRead() + prevBytesReadTotal
|
||||
seg.ResetBytesRead(totalBytesRead)
|
||||
|
||||
for i, segNewDocNums := range newDocNums {
|
||||
if mergedSegHistory[task.Segments[i].Id()] != nil {
|
||||
mergedSegHistory[task.Segments[i].Id()].oldNewDocIDs = segNewDocNums
|
||||
}
|
||||
}
|
||||
|
||||
atomic.AddUint64(&s.stats.TotFileMergeSegments, uint64(len(segmentsToMerge)))
|
||||
if len(batch.segments) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
sm := &segmentMerge{
|
||||
id: []uint64{newSegmentID},
|
||||
mergedSegHistory: mergedSegHistory,
|
||||
new: []segment.Segment{seg},
|
||||
newCount: seg.Count(),
|
||||
notifyCh: make(chan *mergeTaskIntroStatus),
|
||||
mmaped: 1,
|
||||
numMergedSegments += len(batch.snapshots)
|
||||
s.markIneligibleForRemoval(batch.newFilename)
|
||||
path := s.path + string(os.PathSeparator) + batch.newFilename
|
||||
|
||||
prevBytesReadTotal := cumulateBytesRead(batch.segments)
|
||||
fileMergeZapStartTime := time.Now()
|
||||
atomic.AddUint64(&s.stats.TotFileMergeZapBeg, 1)
|
||||
batch.newDocNums, _, err = s.segPlugin.MergeUsing(batch.segments, batch.drops, path,
|
||||
cw.cancelCh, s, s.segmentConfig)
|
||||
atomic.AddUint64(&s.stats.TotFileMergeZapEnd, 1)
|
||||
batch.newTime = uint64(time.Since(fileMergeZapStartTime))
|
||||
atomic.AddUint64(&s.stats.TotFileMergeZapTime, batch.newTime)
|
||||
if atomic.LoadUint64(&s.stats.MaxFileMergeZapTime) < batch.newTime {
|
||||
atomic.StoreUint64(&s.stats.MaxFileMergeZapTime, batch.newTime)
|
||||
}
|
||||
|
||||
s.fireEvent(EventKindMergeTaskIntroductionStart, 0)
|
||||
|
||||
// give it to the introducer
|
||||
select {
|
||||
case <-s.closeCh:
|
||||
_ = seg.Close()
|
||||
err = segment.ErrClosed
|
||||
if err != nil {
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanTasksErr, 1)
|
||||
return err
|
||||
case s.merges <- sm:
|
||||
atomic.AddUint64(&s.stats.TotFileMergeIntroductions, 1)
|
||||
}
|
||||
|
||||
introStartTime := time.Now()
|
||||
// it is safe to blockingly wait for the merge introduction
|
||||
// here as the introducer is bound to handle the notify channel.
|
||||
introStatus := <-sm.notifyCh
|
||||
introTime := uint64(time.Since(introStartTime))
|
||||
atomic.AddUint64(&s.stats.TotFileMergeZapIntroductionTime, introTime)
|
||||
if atomic.LoadUint64(&s.stats.MaxFileMergeZapIntroductionTime) < introTime {
|
||||
atomic.StoreUint64(&s.stats.MaxFileMergeZapIntroductionTime, introTime)
|
||||
batch.new, err = s.segPlugin.OpenUsing(path, s.segmentConfig)
|
||||
if err != nil {
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanTasksErr, 1)
|
||||
return err
|
||||
}
|
||||
atomic.AddUint64(&s.stats.TotFileMergeIntroductionsDone, 1)
|
||||
if introStatus != nil && introStatus.indexSnapshot != nil {
|
||||
_ = introStatus.indexSnapshot.DecRef()
|
||||
if introStatus.skipped {
|
||||
// close the segment on skipping introduction.
|
||||
s.unmarkIneligibleForRemoval(filename)
|
||||
_ = seg.Close()
|
||||
|
||||
totalBytesRead := batch.new.BytesRead() + prevBytesReadTotal
|
||||
batch.new.ResetBytesRead(totalBytesRead)
|
||||
atomic.AddUint64(&s.stats.TotFileMergeSegments, uint64(len(batch.segments)))
|
||||
}
|
||||
|
||||
newSegmentIDs := make([]uint64, numBatches)
|
||||
newSegments := make([]segment.Segment, numBatches)
|
||||
mergedSegHistory := make(map[uint64]*mergedSegmentHistory, numMergedSegments)
|
||||
for batchID := 0; batchID < numBatches; batchID++ {
|
||||
batch := mergeBatches[batchID]
|
||||
newSegmentIDs[batchID] = batch.newID
|
||||
newSegments[batchID] = batch.new
|
||||
for j, ss := range batch.snapshots {
|
||||
mergedSegHistory[ss.id] = &mergedSegmentHistory{
|
||||
batchID: batchID,
|
||||
oldNewDocIDs: batch.newDocNums[j],
|
||||
oldSegment: ss,
|
||||
}
|
||||
}
|
||||
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanTasksDone, 1)
|
||||
|
||||
s.fireEvent(EventKindMergeTaskIntroduction, 0)
|
||||
}
|
||||
|
||||
// once all the newly merged segment introductions are done,
|
||||
// its safe to unflip the removal ineligibility for the replaced
|
||||
// older segments
|
||||
for _, f := range filenames {
|
||||
s.unmarkIneligibleForRemoval(f)
|
||||
sm := &segmentMerge{
|
||||
newSegmentIDs: newSegmentIDs,
|
||||
newSegments: newSegments,
|
||||
mergedSegHistory: mergedSegHistory,
|
||||
notifyCh: make(chan *mergeTaskIntroStatus),
|
||||
mmaped: 1,
|
||||
fileMerge: true,
|
||||
}
|
||||
|
||||
s.fireEvent(EventKindMergeTaskIntroductionStart, 0)
|
||||
// give it to the introducer
|
||||
select {
|
||||
case <-s.closeCh:
|
||||
err = segment.ErrClosed
|
||||
return err
|
||||
case s.merges <- sm:
|
||||
atomic.AddUint64(&s.stats.TotFileMergeIntroductions, uint64(numBatches))
|
||||
}
|
||||
|
||||
introStartTime := time.Now()
|
||||
// it is safe to blockingly wait for the merge introduction
|
||||
// here as the introducer is bound to handle the notify channel.
|
||||
introStatus := <-sm.notifyCh
|
||||
introTime := uint64(time.Since(introStartTime))
|
||||
atomic.AddUint64(&s.stats.TotFileMergeZapIntroductionTime, introTime)
|
||||
if atomic.LoadUint64(&s.stats.MaxFileMergeZapIntroductionTime) < introTime {
|
||||
atomic.StoreUint64(&s.stats.MaxFileMergeZapIntroductionTime, introTime)
|
||||
}
|
||||
atomic.AddUint64(&s.stats.TotFileMergeIntroductionsDone, uint64(numBatches))
|
||||
|
||||
_ = introStatus.indexSnapshot.DecRef()
|
||||
for batchID, skipped := range introStatus.skipped {
|
||||
if skipped {
|
||||
batch := mergeBatches[batchID]
|
||||
if batch.new != nil {
|
||||
_ = batch.new.Close()
|
||||
}
|
||||
s.unmarkIneligibleForRemoval(batch.newFilename)
|
||||
}
|
||||
}
|
||||
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanTasksDone, uint64(numBatches))
|
||||
s.fireEvent(EventKindMergeTaskIntroduction, 0)
|
||||
return nil
|
||||
}
|
||||
|
||||
type mergeTaskIntroStatus struct {
|
||||
indexSnapshot *IndexSnapshot
|
||||
skipped bool
|
||||
skipped []bool
|
||||
}
|
||||
|
||||
// this is important when it comes to introducing multiple merged segments in a
|
||||
// single introducer channel push. That way there is a check to ensure that the
|
||||
// file count doesn't explode during the index's lifetime.
|
||||
type mergedSegmentHistory struct {
|
||||
workerID uint64
|
||||
batchID int
|
||||
oldNewDocIDs []uint64
|
||||
oldSegment *SegmentSnapshot
|
||||
}
|
||||
|
||||
type segmentMerge struct {
|
||||
id []uint64
|
||||
new []segment.Segment
|
||||
newSegmentIDs []uint64
|
||||
newSegments []segment.Segment
|
||||
mergedSegHistory map[uint64]*mergedSegmentHistory
|
||||
notifyCh chan *mergeTaskIntroStatus
|
||||
mmaped uint32
|
||||
newCount uint64
|
||||
fileMerge bool
|
||||
}
|
||||
|
||||
func cumulateBytesRead(sbs []segment.Segment) uint64 {
|
||||
@@ -527,153 +550,179 @@ func cumulateBytesRead(sbs []segment.Segment) uint64 {
|
||||
return rv
|
||||
}
|
||||
|
||||
func closeNewMergedSegments(segs []segment.Segment) error {
|
||||
for _, seg := range segs {
|
||||
if seg != nil {
|
||||
_ = seg.DecRef()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mergeAndPersistInMemorySegments takes an IndexSnapshot and a list of in-memory segments,
|
||||
// which are merged and persisted to disk concurrently. These are then introduced as
|
||||
// the new root snapshot in one-shot.
|
||||
func (s *Scorch) mergeAndPersistInMemorySegments(snapshot *IndexSnapshot,
|
||||
flushableObjs []*flushable) (*IndexSnapshot, []uint64, error) {
|
||||
func (s *Scorch) mergeAndPersistInMemorySegments(flushes []*flushable, po *persisterOptions) (*IndexSnapshot, map[uint64]struct{}, error) {
|
||||
atomic.AddUint64(&s.stats.TotMemMergeBeg, 1)
|
||||
|
||||
memMergeZapStartTime := time.Now()
|
||||
|
||||
atomic.AddUint64(&s.stats.TotMemMergeZapBeg, 1)
|
||||
var err error
|
||||
numBatches := len(flushes)
|
||||
mergeBatches := make([]*mergeBatch, numBatches)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
for batchID := 0; batchID < numBatches; batchID++ {
|
||||
batch := mergeBatches[batchID]
|
||||
if batch.new != nil {
|
||||
_ = batch.new.Close()
|
||||
}
|
||||
s.unmarkIneligibleForRemoval(batch.newFilename)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
var numMergedSegments uint64
|
||||
sem := make(chan struct{}, po.NumPersisterWorkers)
|
||||
var wg sync.WaitGroup
|
||||
// we're tracking the merged segments and their doc number per worker
|
||||
// to be able to introduce them all at once, so the first dimension of the
|
||||
// slices here correspond to workerID
|
||||
newDocIDsSet := make([][][]uint64, len(flushableObjs))
|
||||
newMergedSegments := make([]segment.Segment, len(flushableObjs))
|
||||
newMergedSegmentIDs := make([]uint64, len(flushableObjs))
|
||||
numFlushes := len(flushableObjs)
|
||||
var numSegments, newMergedCount uint64
|
||||
var em sync.Mutex
|
||||
var errM sync.Mutex
|
||||
var errs []error
|
||||
|
||||
// deploy the workers to merge and flush the batches of segments concurrently
|
||||
// and create a new file segment
|
||||
for i := 0; i < numFlushes; i++ {
|
||||
for batchID := 0; batchID < numBatches; batchID++ {
|
||||
wg.Add(1)
|
||||
go func(segsBatch []segment.Segment, dropsBatch []*roaring.Bitmap, id int) {
|
||||
defer wg.Done()
|
||||
newSegmentID := atomic.AddUint64(&s.nextSegmentID, 1)
|
||||
filename := zapFileName(newSegmentID)
|
||||
path := s.path + string(os.PathSeparator) + filename
|
||||
sem <- struct{}{}
|
||||
go func(batchID int) {
|
||||
var err error
|
||||
defer func() {
|
||||
if err != nil {
|
||||
atomic.AddUint64(&s.stats.TotMemMergeErr, 1)
|
||||
errM.Lock()
|
||||
errs = append(errs, err)
|
||||
errM.Unlock()
|
||||
}
|
||||
<-sem
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
// the newly merged segment is already flushed out to disk, just needs
|
||||
// to be opened using mmap.
|
||||
newDocIDs, _, err :=
|
||||
s.segPlugin.MergeUsing(segsBatch, dropsBatch, path, s.closeCh, s, s.segmentConfig)
|
||||
flush := flushes[batchID]
|
||||
newSegmentID := atomic.AddUint64(&s.nextSegmentID, 1)
|
||||
batch := &mergeBatch{
|
||||
snapshots: flush.sbsBatchSnapshots,
|
||||
filenames: nil,
|
||||
segments: flush.sbsBatch,
|
||||
drops: flush.sbsBatchDrops,
|
||||
|
||||
new: nil,
|
||||
newID: newSegmentID,
|
||||
newDocNums: nil,
|
||||
newFilename: zapFileName(newSegmentID),
|
||||
newTime: 0,
|
||||
}
|
||||
mergeBatches[batchID] = batch
|
||||
|
||||
s.markIneligibleForRemoval(batch.newFilename)
|
||||
path := s.path + string(os.PathSeparator) + batch.newFilename
|
||||
|
||||
memMergeZapStartTime := time.Now()
|
||||
atomic.AddUint64(&s.stats.TotMemMergeZapBeg, 1)
|
||||
batch.newDocNums, _, err = s.segPlugin.MergeUsing(batch.segments, batch.drops, path,
|
||||
s.closeCh, s, s.segmentConfig)
|
||||
atomic.AddUint64(&s.stats.TotMemMergeZapEnd, 1)
|
||||
batch.newTime = uint64(time.Since(memMergeZapStartTime))
|
||||
atomic.AddUint64(&s.stats.TotMemMergeZapTime, batch.newTime)
|
||||
if err != nil {
|
||||
em.Lock()
|
||||
errs = append(errs, err)
|
||||
em.Unlock()
|
||||
atomic.AddUint64(&s.stats.TotMemMergeErr, 1)
|
||||
return
|
||||
}
|
||||
// to prevent accidental cleanup of this newly created file, mark it
|
||||
// as ineligible for removal. this will be flipped back when the bolt
|
||||
// is updated - which is valid, since the snapshot updated in bolt is
|
||||
// cleaned up only if its zero ref'd (MB-66163 for more details)
|
||||
s.markIneligibleForRemoval(filename)
|
||||
newMergedSegmentIDs[id] = newSegmentID
|
||||
newDocIDsSet[id] = newDocIDs
|
||||
newMergedSegments[id], err = s.segPlugin.OpenUsing(path, s.segmentConfig)
|
||||
batch.new, err = s.segPlugin.OpenUsing(path, s.segmentConfig)
|
||||
if err != nil {
|
||||
em.Lock()
|
||||
errs = append(errs, err)
|
||||
em.Unlock()
|
||||
atomic.AddUint64(&s.stats.TotMemMergeErr, 1)
|
||||
return
|
||||
}
|
||||
atomic.AddUint64(&newMergedCount, newMergedSegments[id].Count())
|
||||
atomic.AddUint64(&numSegments, uint64(len(segsBatch)))
|
||||
}(flushableObjs[i].segments, flushableObjs[i].drops, i)
|
||||
atomic.AddUint64(&numMergedSegments, uint64(len(batch.segments)))
|
||||
}(batchID)
|
||||
}
|
||||
wg.Wait()
|
||||
close(sem)
|
||||
|
||||
if errs != nil {
|
||||
// close the new merged segments
|
||||
_ = closeNewMergedSegments(newMergedSegments)
|
||||
var errf error
|
||||
for _, err := range errs {
|
||||
if err == segment.ErrClosed {
|
||||
// the index snapshot was closed which will be handled gracefully
|
||||
// by retrying the whole merge+flush operation in a later iteration
|
||||
// so its safe to early exit the same error.
|
||||
return nil, nil, err
|
||||
}
|
||||
errf = fmt.Errorf("%w; %v", errf, err)
|
||||
var maxZapTime uint64
|
||||
for _, batch := range mergeBatches {
|
||||
if batch.newTime > maxZapTime {
|
||||
maxZapTime = batch.newTime
|
||||
}
|
||||
return nil, nil, errf
|
||||
}
|
||||
if maxZapTime > atomic.LoadUint64(&s.stats.MaxMemMergeZapTime) {
|
||||
atomic.StoreUint64(&s.stats.MaxMemMergeZapTime, maxZapTime)
|
||||
}
|
||||
atomic.AddUint64(&s.stats.TotMemMergeSegments, numMergedSegments)
|
||||
|
||||
if len(errs) > 0 {
|
||||
var errf error
|
||||
numClosed := 0
|
||||
for _, e := range errs {
|
||||
if e == segment.ErrClosed {
|
||||
numClosed++
|
||||
}
|
||||
errf = errors.Join(errf, e)
|
||||
}
|
||||
if numClosed == len(errs) {
|
||||
// the index snapshot was closed which will be handled gracefully
|
||||
// by retrying the whole merge+flush operation in a later iteration
|
||||
// so its safe to early exit the same error.
|
||||
err = segment.ErrClosed
|
||||
} else {
|
||||
err = errf
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
atomic.AddUint64(&s.stats.TotMemMergeZapEnd, 1)
|
||||
|
||||
memMergeZapTime := uint64(time.Since(memMergeZapStartTime))
|
||||
atomic.AddUint64(&s.stats.TotMemMergeZapTime, memMergeZapTime)
|
||||
if atomic.LoadUint64(&s.stats.MaxMemMergeZapTime) < memMergeZapTime {
|
||||
atomic.StoreUint64(&s.stats.MaxMemMergeZapTime, memMergeZapTime)
|
||||
}
|
||||
|
||||
// update the segmentMerge task with the newly merged + flushed segments which
|
||||
// are to be introduced atomically.
|
||||
sm := &segmentMerge{
|
||||
id: newMergedSegmentIDs,
|
||||
new: newMergedSegments,
|
||||
mergedSegHistory: make(map[uint64]*mergedSegmentHistory, numSegments),
|
||||
notifyCh: make(chan *mergeTaskIntroStatus),
|
||||
newCount: newMergedCount,
|
||||
}
|
||||
|
||||
// create a history map which maps the old in-memory segments with the specific
|
||||
// persister worker (also the specific file segment its going to be part of)
|
||||
// which flushed it out. This map will be used on the introducer side to out-ref
|
||||
// the in-memory segments and also track the new tombstones if present.
|
||||
for i, flushable := range flushableObjs {
|
||||
for j, idx := range flushable.sbIdxs {
|
||||
ss := snapshot.segment[idx]
|
||||
// oldSegmentSnapshot.id -> {workerID, oldSegmentSnapshot, docIDs}
|
||||
sm.mergedSegHistory[ss.id] = &mergedSegmentHistory{
|
||||
workerID: uint64(i),
|
||||
oldNewDocIDs: newDocIDsSet[i][j],
|
||||
newSegmentIDs := make([]uint64, numBatches)
|
||||
newSegments := make([]segment.Segment, numBatches)
|
||||
mergedSegHistory := make(map[uint64]*mergedSegmentHistory, numMergedSegments)
|
||||
for batchID := 0; batchID < numBatches; batchID++ {
|
||||
batch := mergeBatches[batchID]
|
||||
newSegmentIDs[batchID] = batch.newID
|
||||
newSegments[batchID] = batch.new
|
||||
for j, ss := range batch.snapshots {
|
||||
mergedSegHistory[ss.id] = &mergedSegmentHistory{
|
||||
batchID: batchID,
|
||||
oldNewDocIDs: batch.newDocNums[j],
|
||||
oldSegment: ss,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
select { // send to introducer
|
||||
case <-s.closeCh:
|
||||
_ = closeNewMergedSegments(newMergedSegments)
|
||||
return nil, nil, segment.ErrClosed
|
||||
case s.merges <- sm:
|
||||
sm := &segmentMerge{
|
||||
newSegmentIDs: newSegmentIDs,
|
||||
newSegments: newSegments,
|
||||
mergedSegHistory: mergedSegHistory,
|
||||
notifyCh: make(chan *mergeTaskIntroStatus),
|
||||
mmaped: 1,
|
||||
fileMerge: false,
|
||||
}
|
||||
|
||||
select {
|
||||
case <-s.closeCh:
|
||||
err = segment.ErrClosed
|
||||
return nil, nil, err
|
||||
case s.merges <- sm:
|
||||
atomic.AddUint64(&s.stats.TotMemMergeIntroductions, uint64(numBatches))
|
||||
}
|
||||
|
||||
introStartTime := time.Now()
|
||||
// blockingly wait for the introduction to complete
|
||||
var newSnapshot *IndexSnapshot
|
||||
introStatus := <-sm.notifyCh
|
||||
if introStatus != nil && introStatus.indexSnapshot != nil {
|
||||
newSnapshot = introStatus.indexSnapshot
|
||||
atomic.AddUint64(&s.stats.TotMemMergeSegments, uint64(numSegments))
|
||||
atomic.AddUint64(&s.stats.TotMemMergeDone, 1)
|
||||
if introStatus.skipped {
|
||||
// close the segment on skipping introduction.
|
||||
_ = newSnapshot.DecRef()
|
||||
_ = closeNewMergedSegments(newMergedSegments)
|
||||
newSnapshot = nil
|
||||
introTime := uint64(time.Since(introStartTime))
|
||||
atomic.AddUint64(&s.stats.TotMemMergeZapIntroductionTime, introTime)
|
||||
if atomic.LoadUint64(&s.stats.MaxMemMergeZapIntroductionTime) < introTime {
|
||||
atomic.StoreUint64(&s.stats.MaxMemMergeZapIntroductionTime, introTime)
|
||||
}
|
||||
atomic.AddUint64(&s.stats.TotMemMergeIntroductionsDone, uint64(numBatches))
|
||||
introducedSnapshot := introStatus.indexSnapshot
|
||||
introducedSegmentIDs := make(map[uint64]struct{}, numBatches)
|
||||
for batchID, skipped := range introStatus.skipped {
|
||||
batch := mergeBatches[batchID]
|
||||
if skipped {
|
||||
_ = batch.new.Close()
|
||||
s.unmarkIneligibleForRemoval(batch.newFilename)
|
||||
} else {
|
||||
introducedSegmentIDs[batch.newID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
return newSnapshot, newMergedSegmentIDs, nil
|
||||
atomic.AddUint64(&s.stats.TotMemMergeDone, 1)
|
||||
|
||||
// if we could not introduce all of the newly merged segments,
|
||||
// then we cannot persist a snapshot with any merged segments at all
|
||||
if len(introducedSegmentIDs) != numBatches {
|
||||
_ = introducedSnapshot.DecRef()
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
return introducedSnapshot, introducedSegmentIDs, nil
|
||||
}
|
||||
|
||||
func (s *Scorch) ReportBytesWritten(bytesWritten uint64) {
|
||||
|
||||
+123
-37
@@ -42,6 +42,10 @@ type Segment interface {
|
||||
|
||||
// Size of the persisted segment file.
|
||||
FileSize() int64
|
||||
|
||||
// Size of the persisted segment file
|
||||
// accounting for any logical deletions.
|
||||
LiveFileSize() int64
|
||||
}
|
||||
|
||||
// Plan() will functionally compute a merge plan. A segment will be
|
||||
@@ -54,8 +58,8 @@ func Plan(segments []Segment, o *MergePlanOptions) (*MergePlan, error) {
|
||||
|
||||
// A MergePlan is the result of the Plan() API.
|
||||
//
|
||||
// The planner doesn’t know how or whether these tasks are executed --
|
||||
// that’s up to a separate merge execution system, which might execute
|
||||
// The planner doesn't know how or whether these tasks are executed --
|
||||
// that's up to a separate merge execution system, which might execute
|
||||
// these tasks concurrently or not, and which might execute all the
|
||||
// tasks or not.
|
||||
type MergePlan struct {
|
||||
@@ -71,14 +75,14 @@ type MergeTask struct {
|
||||
// The MergePlanOptions is designed to be reusable between planning calls.
|
||||
type MergePlanOptions struct {
|
||||
// Max # segments per logarithmic tier, or max width of any
|
||||
// logarithmic “step”. Smaller values mean more merging but fewer
|
||||
// logarithmic "step". Smaller values mean more merging but fewer
|
||||
// segments. Should be >= SegmentsPerMergeTask, else you'll have
|
||||
// too much merging.
|
||||
MaxSegmentsPerTier int
|
||||
|
||||
// Max size of any segment produced after merging. Actual
|
||||
// merging, however, may produce segment sizes different than the
|
||||
// planner’s predicted sizes.
|
||||
// planner's predicted sizes.
|
||||
MaxSegmentSize int64
|
||||
|
||||
// Max size (in bytes) of the persisted segment file that contains the
|
||||
@@ -137,6 +141,13 @@ func (o *MergePlanOptions) RaiseToFloorSegmentFileSize(s int64) int64 {
|
||||
return o.FloorSegmentFileSize
|
||||
}
|
||||
|
||||
func (o *MergePlanOptions) BudgetCurrency() BudgetCurrency {
|
||||
if o.FloorSegmentFileSize > 0 {
|
||||
return FileSizeBudget
|
||||
}
|
||||
return LiveSizeBudget
|
||||
}
|
||||
|
||||
// MaxSegmentSizeLimit represents the maximum size of a segment,
|
||||
// this limit comes with hit-1 optimisation/max encoding limit uint31.
|
||||
const MaxSegmentSizeLimit = 1<<31 - 1
|
||||
@@ -149,7 +160,7 @@ var ErrMaxSegmentSizeTooLarge = errors.New("MaxSegmentSize exceeds the size limi
|
||||
var DefaultMergePlanOptions = MergePlanOptions{
|
||||
MaxSegmentsPerTier: 10,
|
||||
MaxSegmentSize: 5000000,
|
||||
MaxSegmentFileSize: 4000000000, // 4GB
|
||||
MaxSegmentFileSize: 4 * 1024 * 1024 * 1024, // 4GiB
|
||||
TierGrowth: 10.0,
|
||||
SegmentsPerMergeTask: 10,
|
||||
FloorSegmentSize: 2000,
|
||||
@@ -171,6 +182,59 @@ var SingleSegmentMergePlanOptions = MergePlanOptions{
|
||||
|
||||
// -------------------------------------------
|
||||
|
||||
// BudgetCurrency is the currency used for budget
|
||||
// calculations in the merge planner.
|
||||
type BudgetCurrency int
|
||||
|
||||
const (
|
||||
// FileSizeBudget uses the file size
|
||||
// of the segments to determine the budget.
|
||||
FileSizeBudget BudgetCurrency = iota
|
||||
|
||||
// LiveSizeBudget uses the live size
|
||||
// of the segments to determine the budget.
|
||||
LiveSizeBudget
|
||||
)
|
||||
|
||||
var ErrUnknownCurrency = errors.New("unknown budget currency")
|
||||
|
||||
// -------------------------------------------
|
||||
|
||||
// rosterCandidate is a potential roster of segments considered while
|
||||
// planning, along with its computed score.
|
||||
type rosterCandidate struct {
|
||||
segments []Segment
|
||||
score float64 // Lower is better.
|
||||
}
|
||||
|
||||
func (c *rosterCandidate) betterThan(other *rosterCandidate) bool {
|
||||
ourSegmentCount := c.count()
|
||||
otherSegmentCount := other.count()
|
||||
// if we have more than one segment and the other has only one, and that
|
||||
// one segment is fully live, then we are better than the other.
|
||||
if ourSegmentCount > 1 && otherSegmentCount == 1 {
|
||||
solo := other.segments[0]
|
||||
if solo.LiveSize() == solo.FullSize() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// if we have only one segment and the other has more than one, and that
|
||||
// one segment is fully live, then we are worse than the other.
|
||||
if ourSegmentCount == 1 && otherSegmentCount > 1 {
|
||||
solo := c.segments[0]
|
||||
if solo.LiveSize() == solo.FullSize() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return c.score < other.score
|
||||
}
|
||||
|
||||
func (c *rosterCandidate) count() int {
|
||||
return len(c.segments)
|
||||
}
|
||||
|
||||
// -------------------------------------------
|
||||
|
||||
func plan(segmentsIn []Segment, o *MergePlanOptions) (*MergePlan, error) {
|
||||
if len(segmentsIn) <= 1 {
|
||||
return nil, nil
|
||||
@@ -185,35 +249,38 @@ func plan(segmentsIn []Segment, o *MergePlanOptions) (*MergePlan, error) {
|
||||
sort.Sort(byLiveSizeDescending(segments))
|
||||
|
||||
var minLiveSize int64 = math.MaxInt64
|
||||
var minLiveFileSize int64 = math.MaxInt64
|
||||
|
||||
var eligibles []Segment
|
||||
var eligiblesLiveSize int64
|
||||
var eligiblesFileSize int64
|
||||
var minFileSize int64 = math.MaxInt64
|
||||
var eligiblesLiveFileSize int64
|
||||
|
||||
for _, segment := range segments {
|
||||
if minLiveSize > segment.LiveSize() {
|
||||
minLiveSize = segment.LiveSize()
|
||||
liveSize := segment.LiveSize()
|
||||
liveFileSize := segment.LiveFileSize()
|
||||
|
||||
if minLiveSize > liveSize {
|
||||
minLiveSize = liveSize
|
||||
}
|
||||
|
||||
if minFileSize > segment.FileSize() {
|
||||
minFileSize = segment.FileSize()
|
||||
if minLiveFileSize > liveFileSize {
|
||||
minLiveFileSize = liveFileSize
|
||||
}
|
||||
|
||||
isEligible := segment.LiveSize() < o.MaxSegmentSize/2
|
||||
isEligible := liveSize < o.MaxSegmentSize/2
|
||||
// An eligible segment (based on #documents) may be too large
|
||||
// and thus need a stricter check based on the file size.
|
||||
// This is particularly important for segments that contain
|
||||
// vectors.
|
||||
if isEligible && segment.HasVector() && o.MaxSegmentFileSize > 0 {
|
||||
isEligible = segment.FileSize() < o.MaxSegmentFileSize/2
|
||||
if segment.HasVector() {
|
||||
isEligible = isEligible && liveFileSize < o.MaxSegmentFileSize/2
|
||||
}
|
||||
|
||||
// Only small-enough segments are eligible.
|
||||
if isEligible {
|
||||
eligibles = append(eligibles, segment)
|
||||
eligiblesLiveSize += segment.LiveSize()
|
||||
eligiblesFileSize += segment.FileSize()
|
||||
eligiblesLiveSize += liveSize
|
||||
eligiblesLiveFileSize += liveFileSize
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,14 +289,18 @@ func plan(segmentsIn []Segment, o *MergePlanOptions) (*MergePlan, error) {
|
||||
calcBudget = CalcBudget
|
||||
}
|
||||
|
||||
var budgetNumSegments int
|
||||
if o.FloorSegmentFileSize > 0 {
|
||||
minFileSize = o.RaiseToFloorSegmentFileSize(minFileSize)
|
||||
budgetNumSegments = calcBudget(eligiblesFileSize, minFileSize, o)
|
||||
currency := o.BudgetCurrency()
|
||||
|
||||
} else {
|
||||
var budgetNumSegments int
|
||||
switch currency {
|
||||
case FileSizeBudget:
|
||||
minLiveFileSize = o.RaiseToFloorSegmentFileSize(minLiveFileSize)
|
||||
budgetNumSegments = calcBudget(eligiblesLiveFileSize, minLiveFileSize, o)
|
||||
case LiveSizeBudget:
|
||||
minLiveSize = o.RaiseToFloorSegmentSize(minLiveSize)
|
||||
budgetNumSegments = calcBudget(eligiblesLiveSize, minLiveSize, o)
|
||||
default:
|
||||
return nil, ErrUnknownCurrency
|
||||
}
|
||||
|
||||
scoreSegments := o.ScoreSegments
|
||||
@@ -250,54 +321,69 @@ func plan(segmentsIn []Segment, o *MergePlanOptions) (*MergePlan, error) {
|
||||
eligibles = removeSegments(eligibles, empties)
|
||||
}
|
||||
|
||||
// While we’re over budget, keep looping, which might produce
|
||||
numMergeTasks := 0
|
||||
|
||||
// While we're over budget, keep looping, which might produce
|
||||
// another MergeTask.
|
||||
for len(eligibles) > 0 && (len(eligibles)+len(rv.Tasks)) > budgetNumSegments {
|
||||
// Track a current best roster as we examine and score
|
||||
for len(eligibles) > 0 && (len(eligibles)+numMergeTasks) > budgetNumSegments {
|
||||
// Track the current best candidate as we examine and score
|
||||
// potential rosters of merges.
|
||||
var bestRoster []Segment
|
||||
var bestRosterScore float64 // Lower score is better.
|
||||
var best *rosterCandidate
|
||||
|
||||
for startIdx := 0; startIdx < len(eligibles); startIdx++ {
|
||||
var roster []Segment
|
||||
var rosterLiveSize int64
|
||||
var rosterFileSize int64 // useful for segments with vectors
|
||||
var rosterLiveFileSize int64
|
||||
|
||||
for idx := startIdx; idx < len(eligibles) && len(roster) < o.SegmentsPerMergeTask; idx++ {
|
||||
eligible := eligibles[idx]
|
||||
|
||||
if rosterLiveSize+eligible.LiveSize() >= o.MaxSegmentSize {
|
||||
liveSize := eligible.LiveSize()
|
||||
|
||||
if rosterLiveSize+liveSize >= o.MaxSegmentSize {
|
||||
continue
|
||||
}
|
||||
|
||||
if eligible.HasVector() {
|
||||
efs := eligible.FileSize()
|
||||
if rosterFileSize+efs >= o.MaxSegmentFileSize {
|
||||
liveFileSize := eligible.LiveFileSize()
|
||||
|
||||
if rosterLiveFileSize+liveFileSize >= o.MaxSegmentFileSize {
|
||||
continue
|
||||
}
|
||||
rosterFileSize += efs
|
||||
|
||||
rosterLiveFileSize += liveFileSize
|
||||
}
|
||||
|
||||
roster = append(roster, eligible)
|
||||
rosterLiveSize += eligible.LiveSize()
|
||||
|
||||
rosterLiveSize += liveSize
|
||||
}
|
||||
|
||||
if len(roster) > 0 {
|
||||
rosterScore := scoreSegments(roster, o)
|
||||
|
||||
if len(bestRoster) == 0 || rosterScore < bestRosterScore {
|
||||
bestRoster = roster
|
||||
bestRosterScore = rosterScore
|
||||
candidate := &rosterCandidate{
|
||||
segments: roster,
|
||||
score: rosterScore,
|
||||
}
|
||||
|
||||
if best == nil || candidate.betterThan(best) {
|
||||
best = candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(bestRoster) == 0 {
|
||||
if best == nil {
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
bestRoster := best.segments
|
||||
|
||||
// create tasks with valid merges - i.e. there should be at least 2 non-empty segments
|
||||
if len(bestRoster) > 1 {
|
||||
// or the bestRoster should have 1 segment with deletes to reclaim.
|
||||
if len(bestRoster) > 1 || bestRoster[0].LiveSize() < bestRoster[0].FullSize() {
|
||||
rv.Tasks = append(rv.Tasks, &MergeTask{Segments: bestRoster})
|
||||
numMergeTasks++
|
||||
}
|
||||
|
||||
eligibles = removeSegments(eligibles, bestRoster)
|
||||
|
||||
+12
-22
@@ -308,24 +308,6 @@ func (o *OptimizeTFRDisjunctionUnadorned) Finish() (rv index.Optimized, err erro
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
for i := range o.snapshot.segment {
|
||||
var cMax uint64
|
||||
|
||||
for _, tfr := range o.tfrs {
|
||||
itr, ok := tfr.iterators[i].(segment.OptimizablePostingsIterator)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if itr.ActualBitmap() != nil {
|
||||
c := itr.ActualBitmap().GetCardinality()
|
||||
if cMax < c {
|
||||
cMax = c
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We use an artificial term and field because the optimized
|
||||
// termFieldReader can represent multiple terms and fields.
|
||||
oTFR := o.snapshot.unadornedTermFieldReader(
|
||||
@@ -362,10 +344,18 @@ func (o *OptimizeTFRDisjunctionUnadorned) Finish() (rv index.Optimized, err erro
|
||||
bm = roaring.Or(actualBMs[0], actualBMs[1])
|
||||
} else if len(actualBMs) == 1 {
|
||||
bm = actualBMs[0].Clone()
|
||||
}
|
||||
|
||||
if bm == nil {
|
||||
bm = roaring.New()
|
||||
} else {
|
||||
if len(docNums) == 0 {
|
||||
// no hits, reuse the zero-alloc empty sentinel
|
||||
oTFR.iterators[i] = anEmptyPostingsIterator
|
||||
continue
|
||||
} else if len(docNums) == 1 {
|
||||
// 1-hit optimized
|
||||
oTFR.iterators[i] = newUnadornedPostingsIteratorFrom1Hit(uint64(docNums[0]))
|
||||
continue
|
||||
} else {
|
||||
bm = roaring.New()
|
||||
}
|
||||
}
|
||||
|
||||
bm.AddMany(docNums)
|
||||
|
||||
+83
-83
@@ -21,7 +21,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/search"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
@@ -36,9 +35,6 @@ type OptimizeVR struct {
|
||||
vrs map[string][]*IndexSnapshotVectorReader
|
||||
}
|
||||
|
||||
// This setting _MUST_ only be changed during init and not after.
|
||||
var BleveMaxKNNConcurrency = 10
|
||||
|
||||
func (o *OptimizeVR) invokeSearcherEndCallback() {
|
||||
if o.ctx != nil {
|
||||
if cb := o.ctx.Value(search.SearcherEndCallbackKey); cb != nil {
|
||||
@@ -54,91 +50,96 @@ func (o *OptimizeVR) invokeSearcherEndCallback() {
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OptimizeVR) Finish() error {
|
||||
// search runs the configured kNN searches for every vector
|
||||
// reader against a single segment, populating the per-segment postings and
|
||||
// iterators on each reader.
|
||||
func (o *OptimizeVR) search(segID int) error {
|
||||
snapshot := o.snapshot.segment[segID]
|
||||
vecSeg, ok := snapshot.segment.(segment_api.VectorSegment)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
meta := snapshot.cachedMeta
|
||||
// for each field, get the vector index --> invoke the zap func.
|
||||
// for each VR, populate postings list and iterators
|
||||
// by passing the obtained vector index and getting similar vectors.
|
||||
// defer close index - just once.
|
||||
var errorsM sync.Mutex
|
||||
var errors []error
|
||||
|
||||
defer o.invokeSearcherEndCallback()
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
semaphore := make(chan struct{}, BleveMaxKNNConcurrency)
|
||||
// Launch goroutines to get vector index for each segment
|
||||
for i, seg := range o.snapshot.segment {
|
||||
if sv, ok := seg.segment.(segment_api.VectorSegment); ok {
|
||||
wg.Add(1)
|
||||
semaphore <- struct{}{} // Acquire a semaphore slot
|
||||
go func(index int, segment segment_api.VectorSegment, origSeg *SegmentSnapshot) {
|
||||
defer func() {
|
||||
<-semaphore // Release the semaphore slot
|
||||
wg.Done()
|
||||
}()
|
||||
for field, vrs := range o.vrs {
|
||||
// Early exit if the field is supposed to be completely deleted or
|
||||
// if it's index data has been deleted
|
||||
if info, ok := o.snapshot.updatedFields[field]; ok && (info.Deleted || info.Index) {
|
||||
continue
|
||||
}
|
||||
|
||||
vecIndex, err := segment.InterpretVectorIndex(field, origSeg.deleted)
|
||||
if err != nil {
|
||||
errorsM.Lock()
|
||||
errors = append(errors, err)
|
||||
errorsM.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// update the vector index size as a meta value in the segment snapshot
|
||||
vectorIndexSize := vecIndex.Size()
|
||||
origSeg.cachedMeta.updateMeta(field, vectorIndexSize)
|
||||
for _, vr := range vrs {
|
||||
var pl segment_api.VecPostingsList
|
||||
var err error
|
||||
|
||||
// for each VR, populate postings list and iterators
|
||||
// by passing the obtained vector index and getting similar vectors.
|
||||
|
||||
// check if the vector reader is configured to use a pre-filter
|
||||
// to filter out ineligible documents before performing
|
||||
// kNN search.
|
||||
if vr.eligibleSelector != nil {
|
||||
pl, err = vecIndex.SearchWithFilter(vr.vector, vr.k,
|
||||
vr.eligibleSelector.SegmentEligibleDocuments(index), vr.searchParams)
|
||||
} else {
|
||||
pl, err = vecIndex.Search(vr.vector, vr.k, vr.searchParams)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
errorsM.Lock()
|
||||
errors = append(errors, err)
|
||||
errorsM.Unlock()
|
||||
go vecIndex.Close()
|
||||
return
|
||||
}
|
||||
|
||||
atomic.AddUint64(&o.snapshot.parent.stats.TotKNNSearches, uint64(1))
|
||||
|
||||
// postings and iterators are already alloc'ed when
|
||||
// IndexSnapshotVectorReader is created
|
||||
vr.postings[index] = pl
|
||||
vr.iterators[index] = pl.Iterator(vr.iterators[index])
|
||||
}
|
||||
go vecIndex.Close()
|
||||
}
|
||||
}(i, sv, seg)
|
||||
for field, vrs := range o.vrs {
|
||||
// Early exit if the field is supposed to be completely deleted or
|
||||
// if it's index data has been deleted
|
||||
if info, ok := o.snapshot.updatedFields[field]; ok && (info.Deleted || info.Index) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
close(semaphore)
|
||||
if len(errors) > 0 {
|
||||
return errors[0]
|
||||
vecIndex, err := vecSeg.InterpretVectorIndex(field, snapshot.deleted)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// update the vector index size as a meta value in the segment snapshot
|
||||
// if not already present
|
||||
if !meta.contains(field) {
|
||||
meta.store(field, vecIndex.Size())
|
||||
}
|
||||
for _, vr := range vrs {
|
||||
var pl segment_api.VecPostingsList
|
||||
var err error
|
||||
// for each VR, populate postings list and iterators
|
||||
// by passing the obtained vector index and getting similar vectors.
|
||||
|
||||
// check if the vector reader is configured to use a pre-filter
|
||||
// to filter out ineligible documents before performing
|
||||
// kNN search.
|
||||
if vr.eligibleSelector != nil {
|
||||
pl, err = vecIndex.SearchWithFilter(
|
||||
vr.vector,
|
||||
vr.k,
|
||||
vr.eligibleSelector.SegmentEligibleDocuments(segID),
|
||||
vr.searchParams,
|
||||
)
|
||||
} else {
|
||||
pl, err = vecIndex.Search(
|
||||
vr.vector,
|
||||
vr.k,
|
||||
vr.searchParams,
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
vecIndex.Close()
|
||||
return err
|
||||
}
|
||||
// postings and iterators are already alloc'ed when
|
||||
// IndexSnapshotVectorReader is created, here we are just
|
||||
// populating them with the obtained postings list.
|
||||
vr.postings[segID] = pl
|
||||
vr.iterators[segID] = pl.Iterator(vr.iterators[segID])
|
||||
}
|
||||
go vecIndex.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *OptimizeVR) Finish() error {
|
||||
defer o.invokeSearcherEndCallback()
|
||||
numSegments := len(o.snapshot.segment)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(numSegments)
|
||||
var errM sync.Mutex
|
||||
var searchErr error
|
||||
// launch goroutines to search the vector index for each segment
|
||||
for i := 0; i < numSegments; i++ {
|
||||
go func(segID int) {
|
||||
defer wg.Done()
|
||||
if err := o.search(segID); err != nil {
|
||||
errM.Lock()
|
||||
searchErr = err
|
||||
errM.Unlock()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
// wait until all the launched goroutines finish and collect errors if any
|
||||
wg.Wait()
|
||||
return searchErr
|
||||
}
|
||||
|
||||
func (s *IndexSnapshotVectorReader) VectorOptimize(ctx context.Context,
|
||||
octx index.VectorOptimizableContext,
|
||||
) (index.VectorOptimizableContext, error) {
|
||||
@@ -173,8 +174,7 @@ func (s *IndexSnapshotVectorReader) VectorOptimize(ctx context.Context,
|
||||
// Finish() logic to even occur or not.
|
||||
var sumVectorIndexSize uint64
|
||||
for _, seg := range o.snapshot.segment {
|
||||
vecIndexSize := seg.cachedMeta.fetchMeta(s.field)
|
||||
if vecIndexSize != nil {
|
||||
if vecIndexSize, ok := seg.cachedMeta.load(s.field); ok {
|
||||
sumVectorIndexSize += vecIndexSize.(uint64)
|
||||
}
|
||||
}
|
||||
|
||||
+351
-399
File diff suppressed because it is too large.
Load diff
+104
-68
@@ -44,6 +44,7 @@ var ErrClosed = fmt.Errorf("scorch closed")
|
||||
type Scorch struct {
|
||||
nextSegmentID uint64
|
||||
stats Stats
|
||||
zapStats segment.Stats
|
||||
iStats internalStats
|
||||
|
||||
readOnly bool
|
||||
@@ -70,6 +71,9 @@ type Scorch struct {
|
||||
// must be accessed within the rootLock as it is accessed by the asynchronous cleanup routine.
|
||||
copyScheduled map[string]int
|
||||
|
||||
persisterOptions *persisterOptions
|
||||
mergePlannerOptions *mergeplan.MergePlanOptions
|
||||
|
||||
numSnapshotsToKeep int
|
||||
rollbackRetentionFactor float64
|
||||
checkPoints []*snapshotMetaData
|
||||
@@ -120,6 +124,9 @@ type trainer interface {
|
||||
// trainer specific file transfer operations
|
||||
copyFileLOCKED(file string, d index.IndexDirectory) error
|
||||
updateBolt(snapshotsBucket *util.BoltBucketImpl, key []byte, value []byte) error
|
||||
|
||||
dropFileWriterIDs(ids map[string]struct{}) error
|
||||
fileWriterIDsInUse() (map[string]struct{}, error)
|
||||
}
|
||||
|
||||
type ScorchErrorType string
|
||||
@@ -130,10 +137,9 @@ func (t ScorchErrorType) Error() string {
|
||||
|
||||
// ErrType values for ScorchError
|
||||
const (
|
||||
ErrAsyncPanic = ScorchErrorType("async panic error")
|
||||
ErrPersist = ScorchErrorType("persist error")
|
||||
ErrCleanup = ScorchErrorType("cleanup error")
|
||||
ErrOptionsParse = ScorchErrorType("options parse error")
|
||||
ErrAsyncPanic = ScorchErrorType("async panic error")
|
||||
ErrPersist = ScorchErrorType("persist error")
|
||||
ErrCleanup = ScorchErrorType("cleanup error")
|
||||
)
|
||||
|
||||
// ScorchError is passed to onAsyncError when errors are
|
||||
@@ -208,6 +214,9 @@ func NewScorch(storeName string,
|
||||
rv.segmentConfig = segConfig
|
||||
}
|
||||
|
||||
// NOTE: always register the stats handler in the config map to track zap layer stats
|
||||
rv.segmentConfig[segment.StatsKey] = &rv.zapStats
|
||||
|
||||
typ, ok := config["spatialPlugin"].(string)
|
||||
if ok {
|
||||
if err := rv.loadSpatialAnalyzerPlugin(typ); err != nil {
|
||||
@@ -232,18 +241,53 @@ func NewScorch(storeName string,
|
||||
if ok {
|
||||
rv.onAsyncError = RegistryAsyncErrorCallbacks[aecbName]
|
||||
}
|
||||
// validate any custom persistor options to
|
||||
// prevent an async error in the persistor routine
|
||||
_, err = rv.parsePersisterOptions()
|
||||
|
||||
rv.numSnapshotsToKeep = NumSnapshotsToKeep
|
||||
if v, ok := rv.config["numSnapshotsToKeep"]; ok {
|
||||
var n int
|
||||
var err error
|
||||
if n, err = parseToInteger(v); err != nil {
|
||||
return nil, fmt.Errorf("numSnapshotsToKeep parse err: %v", err)
|
||||
}
|
||||
if n > 0 {
|
||||
rv.numSnapshotsToKeep = n
|
||||
}
|
||||
}
|
||||
|
||||
rv.rollbackSamplingInterval = RollbackSamplingInterval
|
||||
if v, ok := rv.config["rollbackSamplingInterval"]; ok {
|
||||
var d time.Duration
|
||||
var err error
|
||||
if d, err = parseToTimeDuration(v); err != nil {
|
||||
return nil, fmt.Errorf("rollbackSamplingInterval parse err: %v", err)
|
||||
}
|
||||
rv.rollbackSamplingInterval = d
|
||||
}
|
||||
|
||||
rv.rollbackRetentionFactor = RollbackRetentionFactor
|
||||
if v, ok := rv.config["rollbackRetentionFactor"]; ok {
|
||||
var r float64
|
||||
var err error
|
||||
if r, err = parseToFloat(v); err != nil {
|
||||
return nil, fmt.Errorf("rollbackRetentionFactor parse err: %v", err)
|
||||
}
|
||||
if r < 0 || r > 1 {
|
||||
return nil, fmt.Errorf("rollbackRetentionFactor must be between 0 and 1")
|
||||
}
|
||||
rv.rollbackRetentionFactor = r
|
||||
}
|
||||
|
||||
po, err := rv.parsePersisterOptions()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// validate any custom merge planner options to
|
||||
// prevent an async error in the merger routine
|
||||
_, err = rv.parseMergePlannerOptions()
|
||||
rv.persisterOptions = po
|
||||
|
||||
mpo, err := rv.parseMergePlannerOptions(po)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rv.mergePlannerOptions = mpo
|
||||
|
||||
if trainer := initTrainer(rv, config); trainer != nil {
|
||||
rv.trainer = trainer
|
||||
@@ -328,6 +372,7 @@ func (s *Scorch) openBolt() error {
|
||||
s.unsafeBatch = true
|
||||
}
|
||||
|
||||
// bolt options
|
||||
rootBoltOpt := *bolt.DefaultOptions
|
||||
if s.readOnly {
|
||||
rootBoltOpt.ReadOnly = true
|
||||
@@ -392,42 +437,6 @@ func (s *Scorch) openBolt() error {
|
||||
}
|
||||
}
|
||||
|
||||
s.numSnapshotsToKeep = NumSnapshotsToKeep
|
||||
if v, ok := s.config["numSnapshotsToKeep"]; ok {
|
||||
var t int
|
||||
if t, err = parseToInteger(v); err != nil {
|
||||
return fmt.Errorf("numSnapshotsToKeep parse err: %v", err)
|
||||
}
|
||||
if t > 0 {
|
||||
s.numSnapshotsToKeep = t
|
||||
}
|
||||
}
|
||||
|
||||
s.rollbackSamplingInterval = RollbackSamplingInterval
|
||||
if v, ok := s.config["rollbackSamplingInterval"]; ok {
|
||||
var t time.Duration
|
||||
if t, err = parseToTimeDuration(v); err != nil {
|
||||
return fmt.Errorf("rollbackSamplingInterval parse err: %v", err)
|
||||
}
|
||||
s.rollbackSamplingInterval = t
|
||||
}
|
||||
|
||||
s.rollbackRetentionFactor = RollbackRetentionFactor
|
||||
if v, ok := s.config["rollbackRetentionFactor"]; ok {
|
||||
var r float64
|
||||
if r, ok = v.(float64); ok {
|
||||
return fmt.Errorf("rollbackRetentionFactor parse err: %v", err)
|
||||
}
|
||||
s.rollbackRetentionFactor = r
|
||||
}
|
||||
|
||||
typ, ok := s.config["spatialPlugin"].(string)
|
||||
if ok {
|
||||
if err := s.loadSpatialAnalyzerPlugin(typ); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -570,7 +579,6 @@ func (s *Scorch) Batch(batch *index.Batch) (err error) {
|
||||
|
||||
var newSegment segment.Segment
|
||||
var bufBytes uint64
|
||||
stats := newFieldStats()
|
||||
|
||||
if len(analysisResults) > 0 {
|
||||
newSegment, bufBytes, err = s.segPlugin.NewUsing(analysisResults, s.segmentConfig)
|
||||
@@ -582,14 +590,11 @@ func (s *Scorch) Batch(batch *index.Batch) (err error) {
|
||||
segB.BytesWritten())
|
||||
}
|
||||
atomic.AddUint64(&s.iStats.newSegBufBytesAdded, bufBytes)
|
||||
if fsr, ok := newSegment.(segment.FieldStatsReporter); ok {
|
||||
fsr.UpdateFieldStats(stats)
|
||||
}
|
||||
} else {
|
||||
atomic.AddUint64(&s.stats.TotBatchesEmpty, 1)
|
||||
}
|
||||
|
||||
err = s.prepareSegment(newSegment, ids, batch.InternalOps, batch.PersistedCallback(), stats)
|
||||
err = s.prepareSegment(newSegment, ids, batch.InternalOps, batch.PersistedCallback())
|
||||
if err != nil {
|
||||
if newSegment != nil {
|
||||
_ = newSegment.Close()
|
||||
@@ -632,15 +637,13 @@ func (s *Scorch) Train(batch *index.Batch) error {
|
||||
}
|
||||
|
||||
func (s *Scorch) prepareSegment(newSegment segment.Segment, ids []string,
|
||||
internalOps map[string][]byte, persistedCallback index.BatchCallback, stats *fieldStats,
|
||||
) error {
|
||||
internalOps map[string][]byte, persistedCallback index.BatchCallback) error {
|
||||
// new introduction
|
||||
introduction := &segmentIntroduction{
|
||||
id: atomic.AddUint64(&s.nextSegmentID, 1),
|
||||
data: newSegment,
|
||||
ids: ids,
|
||||
internal: internalOps,
|
||||
stats: stats,
|
||||
applied: make(chan error),
|
||||
persistedCallback: persistedCallback,
|
||||
}
|
||||
@@ -854,6 +857,9 @@ func (s *Scorch) StatsMap() map[string]interface{} {
|
||||
m["field:"+fieldName+":"+statName] = val
|
||||
}
|
||||
}
|
||||
|
||||
// zap layer stats that are continously updated throughout the index lifecycle
|
||||
m[segment.StatsKey] = s.zapStats.StatsMap()
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -1009,6 +1015,20 @@ func parseToInteger(i interface{}) (int, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func parseToFloat(i interface{}) (float64, error) {
|
||||
switch v := i.(type) {
|
||||
case float64:
|
||||
return v, nil
|
||||
case float32:
|
||||
return float64(v), nil
|
||||
case int:
|
||||
return float64(v), nil
|
||||
|
||||
default:
|
||||
return 0, fmt.Errorf("expects float64, float32 or int value")
|
||||
}
|
||||
}
|
||||
|
||||
// Holds Zap's field level stats at a segment level
|
||||
type fieldStats struct {
|
||||
// StatName -> FieldName -> value
|
||||
@@ -1106,10 +1126,12 @@ func (s *Scorch) SetPathInBolt(key []byte, value []byte) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// currently this is specific to trained index file update
|
||||
err = s.trainer.updateBolt(snapshotsBucket, key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
if s.trainer != nil {
|
||||
// currently this is specific to trained index file update
|
||||
err = s.trainer.updateBolt(snapshotsBucket, key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
@@ -1322,6 +1344,16 @@ func (s *Scorch) FileWriterIDsInUse() (map[string]struct{}, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if s.trainer != nil {
|
||||
trainerKeys, err := s.trainer.fileWriterIDsInUse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, _ := range trainerKeys {
|
||||
keyMap[k] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
boltKeys, err := s.boltFileWriterIDsInUse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1344,6 +1376,13 @@ func (s *Scorch) DropFileWriterIDs(ids map[string]struct{}) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.trainer != nil {
|
||||
err := s.trainer.dropFileWriterIDs(ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
s.rootLock.Lock()
|
||||
// create a done channel to ensure success of merge
|
||||
ctx := context.Background()
|
||||
@@ -1357,6 +1396,12 @@ func (s *Scorch) DropFileWriterIDs(ids map[string]struct{}) error {
|
||||
// data with writer ids that have been removed
|
||||
prevNumSnapshotsToKeep := s.numSnapshotsToKeep
|
||||
s.numSnapshotsToKeep = 1
|
||||
defer func() {
|
||||
// reset rollback snapshot retention
|
||||
s.rootLock.Lock()
|
||||
s.numSnapshotsToKeep = prevNumSnapshotsToKeep
|
||||
s.rootLock.Unlock()
|
||||
}()
|
||||
|
||||
// track the zapx files that are expected to be removed after
|
||||
// the merge so that we can block until they are removed by the persister
|
||||
@@ -1365,10 +1410,6 @@ func (s *Scorch) DropFileWriterIDs(ids map[string]struct{}) error {
|
||||
var mergePlanner mergePlanFunc = func(ourSnapshot *IndexSnapshot) (*mergeplan.MergePlan, error) {
|
||||
// Create a merge plan with the filtered segments and force a merge
|
||||
// to remove the callback from the segments.
|
||||
mergePlannerOptions, err := s.parseMergePlannerOptions()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mergePlannerOption json parsing err: %v", err)
|
||||
}
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlan, 1)
|
||||
|
||||
// filter all segments that have callbacks that need to be removed
|
||||
@@ -1387,7 +1428,7 @@ func (s *Scorch) DropFileWriterIDs(ids map[string]struct{}) error {
|
||||
}
|
||||
|
||||
// attempt a merge plan with the default merge planner options
|
||||
mergePlan, err := mergeplan.Plan(segsToCompact, mergePlannerOptions)
|
||||
mergePlan, err := mergeplan.Plan(segsToCompact, s.mergePlannerOptions)
|
||||
if err != nil {
|
||||
atomic.AddUint64(&s.stats.TotFileMergePlanErr, 1)
|
||||
return nil, fmt.Errorf("merge plan creation err: %v", err)
|
||||
@@ -1450,11 +1491,6 @@ func (s *Scorch) DropFileWriterIDs(ids map[string]struct{}) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// reset rollback snapshot retention
|
||||
s.rootLock.Lock()
|
||||
s.numSnapshotsToKeep = prevNumSnapshotsToKeep
|
||||
s.rootLock.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+233
-35
@@ -27,6 +27,8 @@ import (
|
||||
|
||||
"github.com/RoaringBitmap/roaring/v2"
|
||||
"github.com/blevesearch/bleve/v2/document"
|
||||
geov2 "github.com/blevesearch/bleve/v2/geov2"
|
||||
"github.com/blevesearch/bleve/v2/size"
|
||||
"github.com/blevesearch/bleve/v2/util"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
@@ -50,6 +52,8 @@ type asynchSegmentResult struct {
|
||||
}
|
||||
|
||||
var reflectStaticSizeIndexSnapshot int
|
||||
var reflectStaticSizeIndexSnapshotGeoShapeV2Reader int
|
||||
var reflectStaticSizeRoaringIntIterator int
|
||||
|
||||
func init() {
|
||||
var is interface{} = IndexSnapshot{}
|
||||
@@ -63,6 +67,10 @@ func init() {
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("levenshtein automaton ed2 builder err: %v", err))
|
||||
}
|
||||
var gcr IndexSnapshotGeoShapeV2Reader
|
||||
reflectStaticSizeIndexSnapshotGeoShapeV2Reader = int(reflect.TypeOf(gcr).Size())
|
||||
var rip roaring.IntIterator
|
||||
reflectStaticSizeRoaringIntIterator = int(reflect.TypeOf(rip).Size())
|
||||
}
|
||||
|
||||
type IndexSnapshot struct {
|
||||
@@ -329,8 +337,9 @@ func (is *IndexSnapshot) fieldDictRegexp(field string,
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
fd, err := is.newIndexSnapshotFieldDict(field, func(is segment.TermDictionary) segment.DictionaryIterator {
|
||||
return is.AutomatonIterator(a, prefixBeg, prefixEnd)
|
||||
fd, err := is.newIndexSnapshotFieldDict(field, func(dict segment.TermDictionary) segment.DictionaryIterator {
|
||||
// regexp/wildcard candidate collection discards DictEntry.Count.
|
||||
return automatonIteratorOmitCount(dict, a, prefixBeg, prefixEnd)
|
||||
}, false)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -379,8 +388,9 @@ func (is *IndexSnapshot) fieldDictFuzzy(field string,
|
||||
prefixBeg = []byte(prefix)
|
||||
prefixEnd = calculateExclusiveEndFromPrefix(prefixBeg)
|
||||
}
|
||||
fd, err := is.newIndexSnapshotFieldDict(field, func(is segment.TermDictionary) segment.DictionaryIterator {
|
||||
return is.AutomatonIterator(a, prefixBeg, prefixEnd)
|
||||
fd, err := is.newIndexSnapshotFieldDict(field, func(dict segment.TermDictionary) segment.DictionaryIterator {
|
||||
// fuzzy candidate collection discards DictEntry.Count.
|
||||
return automatonIteratorOmitCount(dict, a, prefixBeg, prefixEnd)
|
||||
}, false)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -505,10 +515,7 @@ func (is *IndexSnapshot) Document(id string) (rv index.Document, err error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
docNum, err := next.ID.Value()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
docNum := next.ID.Value()
|
||||
segmentIndex, localDocNum := is.segmentIndexAndLocalDocNumFromGlobal(docNum)
|
||||
|
||||
rvd := document.NewDocument(id)
|
||||
@@ -575,10 +582,7 @@ func (is *IndexSnapshot) segmentIndexAndLocalDocNumFromGlobal(docNum uint64) (in
|
||||
}
|
||||
|
||||
func (is *IndexSnapshot) ExternalID(id index.IndexInternalID) (string, error) {
|
||||
docNum, err := id.Value()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
docNum := id.Value()
|
||||
segmentIndex, localDocNum := is.segmentIndexAndLocalDocNumFromGlobal(docNum)
|
||||
|
||||
v, err := is.segment[segmentIndex].DocID(localDocNum)
|
||||
@@ -593,10 +597,7 @@ func (is *IndexSnapshot) ExternalID(id index.IndexInternalID) (string, error) {
|
||||
}
|
||||
|
||||
func (is *IndexSnapshot) segmentIndexAndLocalDocNum(id index.IndexInternalID) (int, uint64, error) {
|
||||
docNum, err := id.Value()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
docNum := id.Value()
|
||||
segIdx, localDocNum := is.segmentIndexAndLocalDocNumFromGlobal(docNum)
|
||||
return segIdx, localDocNum, nil
|
||||
}
|
||||
@@ -800,8 +801,8 @@ func (is *IndexSnapshot) documentVisitFieldTermsOnSegment(
|
||||
}
|
||||
|
||||
// Filter out fields that have been completely deleted or had their
|
||||
// docvalues data deleted from both visitable fields and required fields
|
||||
filterUpdatedFields := func(fields []string) []string {
|
||||
// docvalues data deleted from the visitable fields
|
||||
filterUpdatedDVFields := func(fields []string) []string {
|
||||
filteredFields := make([]string, 0, len(fields))
|
||||
for _, field := range fields {
|
||||
if info, ok := is.updatedFields[field]; ok &&
|
||||
@@ -813,9 +814,22 @@ func (is *IndexSnapshot) documentVisitFieldTermsOnSegment(
|
||||
return filteredFields
|
||||
}
|
||||
|
||||
// Filter out fields that have been completely deleted or had their
|
||||
// index data deleted from the cached fields
|
||||
filterUpdatedIndexFields := func(fields []string) []string {
|
||||
filteredFields := make([]string, 0, len(fields))
|
||||
for _, field := range fields {
|
||||
if info, ok := is.updatedFields[field]; ok &&
|
||||
(info.Index || info.Deleted) {
|
||||
continue
|
||||
}
|
||||
filteredFields = append(filteredFields, field)
|
||||
}
|
||||
return filteredFields
|
||||
}
|
||||
|
||||
if len(is.updatedFields) > 0 {
|
||||
fields = filterUpdatedFields(fields)
|
||||
vFields = filterUpdatedFields(vFields)
|
||||
vFields = filterUpdatedDVFields(vFields)
|
||||
}
|
||||
|
||||
var errCh chan error
|
||||
@@ -826,18 +840,21 @@ func (is *IndexSnapshot) documentVisitFieldTermsOnSegment(
|
||||
// from a previous invocation
|
||||
if cFields == nil {
|
||||
cFields = subtractStrings(fields, vFields)
|
||||
}
|
||||
if len(is.updatedFields) > 0 {
|
||||
cFields = filterUpdatedIndexFields(cFields)
|
||||
}
|
||||
|
||||
if len(cFields) > 0 && !ss.cachedDocs.hasFields(cFields) {
|
||||
errCh = make(chan error, 1)
|
||||
if len(cFields) > 0 && !ss.cachedDocs.hasFields(cFields) {
|
||||
errCh = make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
err := ss.cachedDocs.prepareFields(cFields, ss)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
close(errCh)
|
||||
}()
|
||||
}
|
||||
go func() {
|
||||
err := ss.cachedDocs.prepareFields(cFields, ss)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
close(errCh)
|
||||
}()
|
||||
}
|
||||
|
||||
if ssvOk && ssv != nil && len(vFields) > 0 {
|
||||
@@ -886,10 +903,7 @@ func (dvr *DocValueReader) BytesRead() uint64 {
|
||||
func (dvr *DocValueReader) VisitDocValues(id index.IndexInternalID,
|
||||
visitor index.DocValueVisitor,
|
||||
) (err error) {
|
||||
docNum, err := id.Value()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
docNum := id.Value()
|
||||
|
||||
segmentIndex, localDocNum := dvr.i.segmentIndexAndLocalDocNumFromGlobal(docNum)
|
||||
if segmentIndex >= len(dvr.i.segment) {
|
||||
@@ -1010,7 +1024,7 @@ func (is *IndexSnapshot) CopyTo(d index.Directory) error {
|
||||
return err
|
||||
}
|
||||
|
||||
_, _, err = prepareBoltSnapshot(is, tx, "", is.parent.segPlugin, nil, d)
|
||||
_, _, err = prepareBoltSnapshot(is, tx, "", is.parent.segPlugin, d)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
return fmt.Errorf("error backing up index snapshot: %v", err)
|
||||
@@ -1304,3 +1318,187 @@ func (i *IndexSnapshot) Ancestors(ID index.IndexInternalID, prealloc []index.Anc
|
||||
// return adjusted ancestors
|
||||
return prealloc, nil
|
||||
}
|
||||
|
||||
func (i *IndexSnapshot) GeoShapeV2FieldReader(ctx context.Context, field string) (
|
||||
index.GeoShapeV2FieldReader, error) {
|
||||
|
||||
rv := &IndexSnapshotGeoShapeV2Reader{
|
||||
field: field,
|
||||
postings: make([]*roaring.Bitmap, len(i.segment)),
|
||||
iterators: make([]roaring.IntPeekable, len(i.segment)),
|
||||
snapshot: i,
|
||||
}
|
||||
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
type IndexSnapshotGeoShapeV2Reader struct {
|
||||
field string
|
||||
|
||||
postings []*roaring.Bitmap
|
||||
iterators []roaring.IntPeekable
|
||||
segmentOffset int
|
||||
|
||||
snapshot *IndexSnapshot
|
||||
}
|
||||
|
||||
// Search performs a spatial search for the given GeoJSON shape and relation
|
||||
// across all segments in the index snapshot.
|
||||
func (g *IndexSnapshotGeoShapeV2Reader) Search(shape index.GeoJSON,
|
||||
relation string) error {
|
||||
|
||||
numSegments := len(g.snapshot.segment)
|
||||
// create a single query object that is thread safe
|
||||
// to be used across all segments
|
||||
query := geov2.NewQuery(shape, relation)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(numSegments)
|
||||
|
||||
var errm sync.Mutex
|
||||
var err error
|
||||
// search each segment concurrently
|
||||
for i := 0; i < numSegments; i++ {
|
||||
go func(segID int) {
|
||||
defer wg.Done()
|
||||
err2 := g.searchSeg(segID, query)
|
||||
if err2 != nil {
|
||||
errm.Lock()
|
||||
if err == nil {
|
||||
err = err2
|
||||
}
|
||||
errm.Unlock()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// searchSeg performs a spatial search for the given GeoJSON shape and relation
|
||||
// on a single segment in the index snapshot.
|
||||
func (g *IndexSnapshotGeoShapeV2Reader) searchSeg(segID int,
|
||||
query geov2.Query) error {
|
||||
|
||||
snapshot := g.snapshot.segment[segID]
|
||||
geoSeg, ok := snapshot.segment.(segment.GeoShapeV2Segment)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
// obtain the geo shape data from the segment
|
||||
geoData, err := geoSeg.GeoShapeV2Data(g.field, snapshot.deleted)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// return if segment does not have any geo shape data for the field
|
||||
if geoData == nil {
|
||||
return nil
|
||||
}
|
||||
// release the reference on the segment's cached geo data once the
|
||||
// evaluation is done, so that the cache is free to evict it
|
||||
defer geoData.Close()
|
||||
|
||||
// evaluate the query against the geo shape data to
|
||||
// get the matching document IDs
|
||||
hits := query.Evaluate(geoData)
|
||||
postings := roaring.New()
|
||||
|
||||
docNums := geoData.DocNums()
|
||||
|
||||
addFunc := func(docNumInternal int) {
|
||||
postings.Add(docNums[docNumInternal])
|
||||
}
|
||||
|
||||
hits.Iterate(addFunc)
|
||||
|
||||
g.postings[segID] = postings
|
||||
g.iterators[segID] = postings.Iterator()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Next returns the next GeoShapeV2FieldDoc from the postings list across all segments in the index snapshot.
|
||||
func (g *IndexSnapshotGeoShapeV2Reader) Next(preAlloced *index.GeoShapeV2FieldDoc) (
|
||||
*index.GeoShapeV2FieldDoc, error) {
|
||||
rv := preAlloced
|
||||
if rv == nil {
|
||||
rv = &index.GeoShapeV2FieldDoc{}
|
||||
}
|
||||
|
||||
for g.segmentOffset < len(g.iterators) {
|
||||
if !g.iterators[g.segmentOffset].HasNext() {
|
||||
g.segmentOffset++
|
||||
continue
|
||||
}
|
||||
|
||||
next := g.iterators[g.segmentOffset].Next()
|
||||
globalOffset := g.snapshot.offsets[g.segmentOffset]
|
||||
rv.ID = index.NewIndexInternalID(rv.ID, uint64(next)+globalOffset)
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Advance moves the reader to the specified document ID, returning the corresponding GeoShapeV2FieldDoc if it exists.
|
||||
func (g *IndexSnapshotGeoShapeV2Reader) Advance(ID index.IndexInternalID,
|
||||
preAlloced *index.GeoShapeV2FieldDoc) (*index.GeoShapeV2FieldDoc, error) {
|
||||
rv := preAlloced
|
||||
if rv == nil {
|
||||
rv = &index.GeoShapeV2FieldDoc{}
|
||||
}
|
||||
|
||||
num := ID.Value()
|
||||
|
||||
segIdx, localDocNum := g.snapshot.segmentIndexAndLocalDocNumFromGlobal(num)
|
||||
if segIdx >= len(g.iterators) {
|
||||
return nil, fmt.Errorf("error advancing to doc number %d, segment "+
|
||||
"index %d out of bounds", num, segIdx)
|
||||
}
|
||||
|
||||
if g.segmentOffset > segIdx {
|
||||
return nil, fmt.Errorf("error advancing to doc number %d, segment "+
|
||||
"index %d is less than current segment offset %d", num, segIdx, g.segmentOffset)
|
||||
}
|
||||
|
||||
g.segmentOffset = segIdx
|
||||
g.iterators[g.segmentOffset].AdvanceIfNeeded(uint32(localDocNum))
|
||||
|
||||
return g.Next(rv)
|
||||
}
|
||||
|
||||
// Close is a no-op: the reader holds no resources of its own, and the
|
||||
// segment-level geo data it reads from is owned and evicted by the
|
||||
// segment's cache
|
||||
func (g *IndexSnapshotGeoShapeV2Reader) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Count returns the total number of documents across all segments
|
||||
// in the index snapshot that match the GeoShapeV2FieldReader's criteria.
|
||||
func (g *IndexSnapshotGeoShapeV2Reader) Count() uint64 {
|
||||
var rv uint64
|
||||
for _, posting := range g.postings {
|
||||
if posting != nil {
|
||||
rv += uint64(posting.GetCardinality())
|
||||
}
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
// Size returns the estimated size in bytes of the
|
||||
// IndexSnapshotGeoShapeV2Reader, including its postings and iterators.
|
||||
func (g *IndexSnapshotGeoShapeV2Reader) Size() int {
|
||||
rv := reflectStaticSizeIndexSnapshotGeoShapeV2Reader + size.SizeOfPtr +
|
||||
len(g.field) + size.SizeOfInt
|
||||
|
||||
for _, posting := range g.postings {
|
||||
rv += int(posting.GetSizeInBytes())
|
||||
}
|
||||
|
||||
rv += (reflectStaticSizeRoaringIntIterator + size.SizeOfPtr) * len(g.iterators)
|
||||
|
||||
return rv
|
||||
}
|
||||
+20
@@ -21,6 +21,26 @@ import (
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
// termDictionaryOmitCount is an optional interface a segment's TermDictionary
|
||||
// may implement to return an automaton iterator that skips the per-term
|
||||
// postings read used to populate DictEntry.Count. It is used by candidate-term
|
||||
// collection (fuzzy/regexp) where the count is discarded, and falls back to the
|
||||
// regular AutomatonIterator when the segment does not implement it.
|
||||
type termDictionaryOmitCount interface {
|
||||
AutomatonIteratorOmitCount(a segment.Automaton,
|
||||
startKeyInclusive, endKeyExclusive []byte) segment.DictionaryIterator
|
||||
}
|
||||
|
||||
// automatonIteratorOmitCount returns a count-omitting automaton iterator when
|
||||
// the dictionary supports it, otherwise the standard one.
|
||||
func automatonIteratorOmitCount(dict segment.TermDictionary, a segment.Automaton,
|
||||
startKeyInclusive, endKeyExclusive []byte) segment.DictionaryIterator {
|
||||
if oc, ok := dict.(termDictionaryOmitCount); ok {
|
||||
return oc.AutomatonIteratorOmitCount(a, startKeyInclusive, endKeyExclusive)
|
||||
}
|
||||
return dict.AutomatonIterator(a, startKeyInclusive, endKeyExclusive)
|
||||
}
|
||||
|
||||
type segmentDictCursor struct {
|
||||
dict segment.TermDictionary
|
||||
itr segment.DictionaryIterator
|
||||
|
||||
+1
-4
@@ -181,10 +181,7 @@ func (i *IndexSnapshotTermFieldReader) Advance(ID index.IndexInternalID, preAllo
|
||||
}
|
||||
}
|
||||
}
|
||||
num, err := ID.Value()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error converting to doc number % x - %v", ID, err)
|
||||
}
|
||||
num := ID.Value()
|
||||
segIndex, ldocNum := i.snapshot.segmentIndexAndLocalDocNumFromGlobal(num)
|
||||
if segIndex >= len(i.snapshot.segment) {
|
||||
return nil, fmt.Errorf("computed segment index %d out of bounds %d",
|
||||
|
||||
+5
-5
@@ -23,6 +23,7 @@ import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/size"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
@@ -123,10 +124,7 @@ func (i *IndexSnapshotVectorReader) Advance(ID index.IndexInternalID,
|
||||
*i = *(i2.(*IndexSnapshotVectorReader))
|
||||
}
|
||||
|
||||
num, err := ID.Value()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error converting to doc number % x - %v", ID, err)
|
||||
}
|
||||
num := ID.Value()
|
||||
segIndex, ldocNum := i.snapshot.segmentIndexAndLocalDocNumFromGlobal(num)
|
||||
if segIndex >= len(i.snapshot.segment) {
|
||||
return nil, fmt.Errorf("computed segment index %d out of bounds %d",
|
||||
@@ -164,7 +162,9 @@ func (i *IndexSnapshotVectorReader) Count() uint64 {
|
||||
}
|
||||
|
||||
func (i *IndexSnapshotVectorReader) Close() error {
|
||||
// TODO Consider if any scope of recycling here.
|
||||
if i.snapshot != nil {
|
||||
atomic.AddUint64(&i.snapshot.parent.stats.TotKNNSearches, 1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+53
-34
@@ -38,16 +38,14 @@ type SegmentSnapshot struct {
|
||||
creator string
|
||||
stats *fieldStats
|
||||
|
||||
// if this segment is in-memory then we'll try to undo the internal values
|
||||
// in the indexSnapshot internal map before updating the bolt, since its
|
||||
// supposed to be reflective of the on-disk data.
|
||||
internal map[string][]byte
|
||||
|
||||
updatedFields map[string]*index.UpdateFieldInfo
|
||||
|
||||
cachedMeta *cachedMeta
|
||||
|
||||
cachedDocs *cachedDocs
|
||||
|
||||
rootCountOnce sync.Once
|
||||
rootCount uint64
|
||||
}
|
||||
|
||||
func (s *SegmentSnapshot) Segment() segment.Segment {
|
||||
@@ -95,6 +93,27 @@ func (s *SegmentSnapshot) FileSize() int64 {
|
||||
return fi.Size()
|
||||
}
|
||||
|
||||
func (s *SegmentSnapshot) LiveFileSize() int64 {
|
||||
fullSize := float64(s.FullSize())
|
||||
if fullSize <= 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
liveSize := float64(s.LiveSize())
|
||||
if liveSize <= 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
fileSize := float64(s.FileSize())
|
||||
if fileSize <= 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
liveRatio := liveSize / fullSize
|
||||
|
||||
return int64(fileSize * liveRatio)
|
||||
}
|
||||
|
||||
func (s *SegmentSnapshot) Close() error {
|
||||
return s.segment.Close()
|
||||
}
|
||||
@@ -119,13 +138,14 @@ func (s *SegmentSnapshot) Count() uint64 {
|
||||
// Count() counts all live documents including nested children, whereas this method
|
||||
// counts only root live documents
|
||||
func (s *SegmentSnapshot) CountRoot() uint64 {
|
||||
var rv uint64
|
||||
if nsb, ok := s.segment.(segment.NestedSegment); ok {
|
||||
rv = nsb.CountRoot(s.deleted)
|
||||
} else {
|
||||
rv = s.Count()
|
||||
}
|
||||
return rv
|
||||
s.rootCountOnce.Do(func() {
|
||||
if nsb, ok := s.segment.(segment.NestedSegment); ok {
|
||||
s.rootCount = nsb.CountRoot(s.deleted)
|
||||
} else {
|
||||
s.rootCount = s.Count()
|
||||
}
|
||||
})
|
||||
return s.rootCount
|
||||
}
|
||||
|
||||
func (s *SegmentSnapshot) DocNumbers(docIDs []string) (*roaring.Bitmap, error) {
|
||||
@@ -350,34 +370,33 @@ func (c *cachedDocs) visitDoc(localDocNum uint64,
|
||||
c.m.RUnlock()
|
||||
}
|
||||
|
||||
// the purpose of the cachedMeta is to simply allow the user of this type to record
|
||||
// and cache certain meta data information (specific to the segment) that can be
|
||||
// used across calls to save compute on the same.
|
||||
// for example searcher creations on the same index snapshot can use this struct
|
||||
// to help and fetch the backing index size information which can be used in
|
||||
// memory usage calculation thereby deciding whether to allow a query or not.
|
||||
// cachedMeta is a simple wrapper around sync.Map to provide typed
|
||||
// access to cached metadata values for segments.
|
||||
type cachedMeta struct {
|
||||
m sync.RWMutex
|
||||
meta map[string]interface{}
|
||||
meta sync.Map
|
||||
}
|
||||
|
||||
func (c *cachedMeta) updateMeta(field string, val interface{}) {
|
||||
c.m.Lock()
|
||||
if c.meta == nil {
|
||||
c.meta = make(map[string]interface{})
|
||||
func newCachedMeta() *cachedMeta {
|
||||
return &cachedMeta{
|
||||
meta: sync.Map{},
|
||||
}
|
||||
c.meta[field] = val
|
||||
c.m.Unlock()
|
||||
}
|
||||
|
||||
func (c *cachedMeta) fetchMeta(field string) (rv interface{}) {
|
||||
c.m.RLock()
|
||||
defer c.m.RUnlock()
|
||||
if c.meta == nil {
|
||||
return nil
|
||||
}
|
||||
rv = c.meta[field]
|
||||
return rv
|
||||
// store the value for a field in the cache, overwriting any existing value.
|
||||
func (c *cachedMeta) store(field string, val interface{}) {
|
||||
c.meta.Store(field, val)
|
||||
}
|
||||
|
||||
// load the value for a field from the cache, returning the value
|
||||
// and a boolean indicating whether the value was present.
|
||||
func (c *cachedMeta) load(field string) (rv interface{}, ok bool) {
|
||||
return c.meta.Load(field)
|
||||
}
|
||||
|
||||
// contains reports whether the cache has an entry for the given field.
|
||||
func (c *cachedMeta) contains(field string) bool {
|
||||
_, ok := c.meta.Load(field)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *SegmentSnapshot) Ancestors(docNum uint64, prealloc []index.AncestorID) []index.AncestorID {
|
||||
|
||||
+21
-12
@@ -64,8 +64,6 @@ type Stats struct {
|
||||
TotIntroducePersistEnd uint64
|
||||
TotIntroduceMergeBeg uint64
|
||||
TotIntroduceMergeEnd uint64
|
||||
TotIntroduceRevertBeg uint64
|
||||
TotIntroduceRevertEnd uint64
|
||||
|
||||
TotIntroducedItems uint64
|
||||
TotIntroducedSegmentsBatch uint64
|
||||
@@ -127,18 +125,29 @@ type Stats struct {
|
||||
CurFilesIneligibleForRemoval uint64
|
||||
TotSnapshotsRemovedFromMetaStore uint64
|
||||
|
||||
TotMemMergeBeg uint64
|
||||
TotMemMergeErr uint64
|
||||
TotMemMergeDone uint64
|
||||
TotMemMergeZapBeg uint64
|
||||
TotMemMergeZapEnd uint64
|
||||
TotMemMergeZapTime uint64
|
||||
MaxMemMergeZapTime uint64
|
||||
TotMemMergeSegments uint64
|
||||
TotMemMergeBeg uint64
|
||||
TotMemMergeErr uint64
|
||||
TotMemMergeDone uint64
|
||||
TotMemMergeSegments uint64
|
||||
|
||||
TotMemMergeZapBeg uint64
|
||||
TotMemMergeZapEnd uint64
|
||||
TotMemMergeZapTime uint64
|
||||
MaxMemMergeZapTime uint64
|
||||
TotMemMergeZapIntroductionTime uint64
|
||||
MaxMemMergeZapIntroductionTime uint64
|
||||
|
||||
TotMemMergeIntroductions uint64
|
||||
TotMemMergeIntroductionsDone uint64
|
||||
TotMemMergeIntroductionsSkipped uint64
|
||||
TotMemMergeIntroductionsObsoleted uint64
|
||||
|
||||
TotMemorySegmentsAtRoot uint64
|
||||
|
||||
TotTrainedSamples uint64
|
||||
TotTrainTime uint64
|
||||
TotTrainedSamples uint64
|
||||
TotTrainTime uint64
|
||||
TotTrainFireIndexEventTime uint64
|
||||
TotTrainFireIndexEvents uint64
|
||||
}
|
||||
|
||||
// atomically populates the returned map
|
||||
|
||||
+8
@@ -53,3 +53,11 @@ func (t *noopTrainer) copyFileLOCKED(file string, d index.IndexDirectory) error
|
||||
func (t *noopTrainer) updateBolt(snapshotsBucket *util.BoltBucketImpl, key []byte, value []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *noopTrainer) dropFileWriterIDs(ids map[string]struct{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *noopTrainer) fileWriterIDsInUse() (map[string]struct{}, error) {
|
||||
return nil, nil
|
||||
}
|
||||
+342
-113
@@ -18,7 +18,6 @@
|
||||
package scorch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"maps"
|
||||
@@ -37,10 +36,12 @@ import (
|
||||
)
|
||||
|
||||
type trainRequest struct {
|
||||
finalSample bool
|
||||
sampleSize int
|
||||
ackCh chan error
|
||||
sample segment.Segment
|
||||
finalSample bool
|
||||
sampleSize int
|
||||
ackCh chan error
|
||||
sample segment.Segment
|
||||
trainingParams *index.TrainingParams
|
||||
removedFileWriterIDs map[string]struct{}
|
||||
}
|
||||
|
||||
type vectorTrainer struct {
|
||||
@@ -54,6 +55,10 @@ type vectorTrainer struct {
|
||||
// the data vectors, returns trained centroid layout
|
||||
trainedIndex *SegmentSnapshot
|
||||
trainCh chan *trainRequest
|
||||
// closed by trainLoop when it exits (via close, training completion, or
|
||||
// error). Producers select on it so they never block on a request that the
|
||||
// trainer will never consume/ack.
|
||||
doneCh chan struct{}
|
||||
}
|
||||
|
||||
const IndexTrainedWithFastMerge = "vector_index_fast_merge"
|
||||
@@ -64,8 +69,9 @@ func initTrainer(s *Scorch, config map[string]interface{}) *vectorTrainer {
|
||||
if ok && feature {
|
||||
trainer := vectorTrainer{
|
||||
parent: s,
|
||||
config: maps.Clone(s.config),
|
||||
config: maps.Clone(s.segmentConfig),
|
||||
trainCh: make(chan *trainRequest, 1),
|
||||
doneCh: make(chan struct{}),
|
||||
}
|
||||
// update the parent scorch config with the trainer's callback to fetch the trained index
|
||||
s.segmentConfig[index.TrainedIndexCallback] = index.TrainedIndexCallbackFn(trainer.getTrainedIndex)
|
||||
@@ -100,9 +106,13 @@ func (t *vectorTrainer) persistToBolt(trainReq *trainRequest) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating trained index bucket: %v", err)
|
||||
}
|
||||
err = trainerBucket.Put(util.BoltPathKey, []byte(index.TrainedIndexFileName), nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error updating trained index bucket: %v", err)
|
||||
|
||||
segmentPath := t.parent.path + string(os.PathSeparator) + index.TrainedIndexFileName
|
||||
if _, err := os.Stat(segmentPath); !os.IsNotExist(err) {
|
||||
err = trainerBucket.Put(util.BoltPathKey, []byte(index.TrainedIndexFileName), nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error updating trained index bucket: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
t.trainingComplete.Store(trainReq.finalSample)
|
||||
@@ -125,117 +135,181 @@ func (t *vectorTrainer) persistToBolt(trainReq *trainRequest) error {
|
||||
return t.parent.rootBolt.Sync()
|
||||
}
|
||||
|
||||
// this is not a routine that will be running throughout the lifetime of the index. It's purpose
|
||||
// is to only train the vector index before the data ingestion starts.
|
||||
// trainLoop is not a routine that runs throughout the lifetime of the index.
|
||||
// Its purpose is only to train the vector index before data ingestion starts.
|
||||
// It is the sole consumer of trainCh and the sole owner of trainedIndex
|
||||
// mutations originating from training.
|
||||
func (t *vectorTrainer) trainLoop() {
|
||||
defer t.parent.asyncTasks.Done()
|
||||
// signal any blocked producers that no further requests will be serviced.
|
||||
defer close(t.doneCh)
|
||||
|
||||
trainLoopStartTime := time.Now()
|
||||
start := time.Now()
|
||||
path := filepath.Join(t.parent.path, index.TrainedIndexFileName)
|
||||
// config is owned exclusively by this goroutine. t.config is read
|
||||
// concurrently by train(), so it must not be mutated here.
|
||||
config := maps.Clone(t.config)
|
||||
|
||||
for {
|
||||
// exit once the final sample set has been ingested and training is complete.
|
||||
if t.trainingComplete.Load() {
|
||||
atomic.StoreUint64(&t.parent.stats.TotTrainedSamples, t.trainedSamples)
|
||||
atomic.StoreUint64(&t.parent.stats.TotTrainTime, uint64(time.Since(trainLoopStartTime).Milliseconds()))
|
||||
t.recordTrainingStats(start)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-t.parent.closeCh:
|
||||
select {
|
||||
case req := <-t.trainCh:
|
||||
req.ackCh <- fmt.Errorf("trainer is closed")
|
||||
close(req.ackCh)
|
||||
default:
|
||||
}
|
||||
// the deferred close(doneCh) releases any producer blocked on
|
||||
// trainCh or its ackCh, so there is no need to drain here.
|
||||
return
|
||||
case trainReq := <-t.trainCh:
|
||||
sampleSeg := trainReq.sample
|
||||
// no sample segment: just persist state if this is the final sample and move on.
|
||||
if sampleSeg == nil {
|
||||
if trainReq.finalSample {
|
||||
if err := t.persistToBolt(trainReq); err != nil {
|
||||
trainReq.ackCh <- fmt.Errorf("error persisting to bolt: %v", err)
|
||||
close(trainReq.ackCh)
|
||||
return
|
||||
}
|
||||
}
|
||||
close(trainReq.ackCh)
|
||||
continue
|
||||
}
|
||||
|
||||
if t.trainedIndex == nil {
|
||||
switch seg := sampleSeg.(type) {
|
||||
case segment.UnpersistedSegment:
|
||||
if err := persistToDirectory(seg, nil, path); err != nil {
|
||||
trainReq.ackCh <- fmt.Errorf("error persisting segment: %v", err)
|
||||
close(trainReq.ackCh)
|
||||
continue
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// merge the new segment with the existing one into a .tmp file, then
|
||||
// atomically rename it into place (Os.Open on the live path is unsafe
|
||||
// during the merge).
|
||||
t.config[index.TrainingKey] = true
|
||||
_, _, err := t.parent.segPlugin.MergeUsing([]segment.Segment{t.trainedIndex.segment, sampleSeg},
|
||||
[]*roaring.Bitmap{nil, nil}, path+".tmp", t.parent.closeCh, nil, t.config)
|
||||
t.config[index.TrainingKey] = false
|
||||
if err != nil {
|
||||
trainReq.ackCh <- fmt.Errorf("error merging trained index: %v", err)
|
||||
close(trainReq.ackCh)
|
||||
return
|
||||
}
|
||||
|
||||
t.trainedIndex.segment.Close()
|
||||
if err = moveFile(path+".tmp", path); err != nil {
|
||||
trainReq.ackCh <- fmt.Errorf("error renaming trained index: %v", err)
|
||||
close(trainReq.ackCh)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// bolt write acts as a checkpoint for failover-recovery: callers downstream
|
||||
// can rely on the trained index being available once this completes.
|
||||
// todo: rethink the frequency of bolt writes
|
||||
if err := t.persistToBolt(trainReq); err != nil {
|
||||
trainReq.ackCh <- fmt.Errorf("error persisting to bolt: %v", err)
|
||||
close(trainReq.ackCh)
|
||||
case req := <-t.trainCh:
|
||||
shutdown, err := t.handleRequest(req, path, config)
|
||||
ackRequest(req, err)
|
||||
if shutdown {
|
||||
return
|
||||
}
|
||||
|
||||
trainedIndex, err := t.parent.segPlugin.OpenUsing(path, t.parent.segmentConfig)
|
||||
if err != nil {
|
||||
trainReq.ackCh <- fmt.Errorf("error opening trained index: %v", err)
|
||||
close(trainReq.ackCh)
|
||||
return
|
||||
}
|
||||
|
||||
t.m.Lock()
|
||||
t.trainedIndex = &SegmentSnapshot{segment: trainedIndex}
|
||||
t.m.Unlock()
|
||||
close(trainReq.ackCh)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// loads the metadata specific to the trained index from boltdb, happens during init
|
||||
// no lock needed
|
||||
// recordTrainingStats publishes the final training counters once the loop exits.
|
||||
func (t *vectorTrainer) recordTrainingStats(start time.Time) {
|
||||
atomic.StoreUint64(&t.parent.stats.TotTrainedSamples, atomic.LoadUint64(&t.trainedSamples))
|
||||
atomic.StoreUint64(&t.parent.stats.TotTrainTime, uint64(time.Since(start).Milliseconds()))
|
||||
}
|
||||
|
||||
// ackRequest delivers a request's result to the producer waiting in submit and
|
||||
// then releases it. A non-nil err is sent before the close so submit observes
|
||||
// it; the send blocks until submit receives, which the shutdown handshake in
|
||||
// submit relies on.
|
||||
func ackRequest(req *trainRequest, err error) {
|
||||
if err != nil {
|
||||
req.ackCh <- err
|
||||
}
|
||||
close(req.ackCh)
|
||||
}
|
||||
|
||||
// handleRequest processes a single training request. The returned err, if
|
||||
// non-nil, is already formatted for the producer. shutdown reports whether the
|
||||
// trainLoop must exit: every failure is fatal except a failed initial persist,
|
||||
// which leaves the trainer able to retry on the next sample.
|
||||
func (t *vectorTrainer) handleRequest(req *trainRequest, path string, config map[string]interface{}) (shutdown bool, err error) {
|
||||
if req.trainingParams != nil {
|
||||
// mutate the goroutine-local config only; t.config is read concurrently
|
||||
// by train() and must stay immutable after init.
|
||||
config[index.TrainingKey] = req.trainingParams
|
||||
}
|
||||
|
||||
// remove any file writer ids that are no longer in use
|
||||
if req.removedFileWriterIDs != nil {
|
||||
if err := t.removeFileWriterIDs(req.removedFileWriterIDs); err != nil {
|
||||
return true, fmt.Errorf("error removing file writer ids: %v", err)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// no sample segment: just persist state if this is the final sample.
|
||||
if req.sample == nil {
|
||||
if req.finalSample {
|
||||
if err := t.persistToBolt(req); err != nil {
|
||||
return true, fmt.Errorf("error persisting to bolt: %v", err)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// snapshot the current trained segment under the read lock; MergeUsing below
|
||||
// only reads it, so concurrent getTrainedIndex readers stay safe.
|
||||
t.m.RLock()
|
||||
prev := t.trainedIndex
|
||||
t.m.RUnlock()
|
||||
|
||||
if prev == nil {
|
||||
if seg, ok := req.sample.(segment.UnpersistedSegment); ok {
|
||||
if err := persistToDirectory(seg, nil, path); err != nil {
|
||||
// recoverable: retry on the next sample rather than tear down.
|
||||
return false, fmt.Errorf("error persisting segment: %v", err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// merge the new sample with the existing index into a .tmp file; it is
|
||||
// renamed into place by publishTrainedIndex (Os.Open on the live path is
|
||||
// unsafe during the merge).
|
||||
_, _, mErr := t.parent.segPlugin.MergeUsing([]segment.Segment{prev.segment, req.sample},
|
||||
[]*roaring.Bitmap{nil, nil}, path+".tmp", t.parent.closeCh, nil, config)
|
||||
if mErr != nil {
|
||||
return true, fmt.Errorf("error merging trained index: %v", mErr)
|
||||
}
|
||||
}
|
||||
|
||||
if err := t.publishTrainedIndex(req, prev, path, config); err != nil {
|
||||
return true, err
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// publishTrainedIndex makes the freshly written index visible to readers. The
|
||||
// old segment handle must be closed before moveFile can replace the backing
|
||||
// file, so the close -> rename -> open -> pointer-swap sequence runs under the
|
||||
// write lock; otherwise a reader holding RLock could observe a closed segment
|
||||
// or a missing file. On any error past the close, the pointer is reset to nil
|
||||
// so readers never see the freed prev segment (callers fall back to naive
|
||||
// merge). The bolt write acts as a failover-recovery checkpoint: callers
|
||||
// downstream can rely on the trained index being available once this completes.
|
||||
// todo: rethink the frequency of bolt writes
|
||||
func (t *vectorTrainer) publishTrainedIndex(req *trainRequest, prev *SegmentSnapshot, path string, config map[string]interface{}) error {
|
||||
t.m.Lock()
|
||||
defer t.m.Unlock()
|
||||
|
||||
if prev != nil {
|
||||
if err := prev.segment.Close(); err != nil {
|
||||
t.trainedIndex = nil
|
||||
return fmt.Errorf("error closing previous trained index: %v", err)
|
||||
}
|
||||
if err := moveFile(path+".tmp", path); err != nil {
|
||||
t.trainedIndex = nil
|
||||
return fmt.Errorf("error renaming trained index: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := t.persistToBolt(req); err != nil {
|
||||
if prev != nil {
|
||||
t.trainedIndex = nil
|
||||
}
|
||||
return fmt.Errorf("error persisting to bolt: %v", err)
|
||||
}
|
||||
|
||||
trainedIndex, err := t.parent.segPlugin.OpenUsing(path, config)
|
||||
if err != nil {
|
||||
t.trainedIndex = nil
|
||||
return fmt.Errorf("error opening trained index: %v", err)
|
||||
}
|
||||
t.trainedIndex = &SegmentSnapshot{segment: trainedIndex}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadTrainedData loads the trained-index metadata from boltdb during init. The
|
||||
// trainedIndex write is guarded because callback-driven readers may already be
|
||||
// registered by the time this runs.
|
||||
func (t *vectorTrainer) loadTrainedData(bucket *util.BoltBucketImpl) error {
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
writerID, err := bucket.Get(util.BoltMetaDataFileWriterIDKey, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error getting writer id: %v", err)
|
||||
}
|
||||
reader, err := util.NewFileReader(string(writerID), nil)
|
||||
|
||||
reader, err := util.NewFileReader("", nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating file reader: %v", err)
|
||||
}
|
||||
|
||||
segmentSnapshot, err := t.parent.loadSegment(bucket, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
// segmentSnapshot is constructed only if the trained index file path exists. If
|
||||
// application layer fails to create one and the underlying path doesn't exist, we'll
|
||||
// just skip loading the trained index and fallback to naive merge
|
||||
var segmentSnapshot *SegmentSnapshot
|
||||
pathBytes, err := bucket.Get(util.BoltPathKey, nil)
|
||||
if pathBytes != nil {
|
||||
segmentSnapshot, err = t.parent.loadSegment(bucket, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// get the training status out of bolt
|
||||
@@ -247,12 +321,16 @@ func (t *vectorTrainer) loadTrainedData(bucket *util.BoltBucketImpl) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("error getting trained samples: %v", err)
|
||||
}
|
||||
atomic.StoreUint64(&t.trainedSamples, binary.LittleEndian.Uint64(trainedSamples))
|
||||
comp, err := strconv.ParseBool(string(trainComplete))
|
||||
if err != nil {
|
||||
return fmt.Errorf("error parsing train complete: %v", err)
|
||||
if len(trainedSamples) == 8 {
|
||||
atomic.StoreUint64(&t.trainedSamples, binary.LittleEndian.Uint64(trainedSamples))
|
||||
}
|
||||
if len(trainComplete) > 0 {
|
||||
comp, err := strconv.ParseBool(string(trainComplete))
|
||||
if err != nil {
|
||||
return fmt.Errorf("error parsing train complete: %v", err)
|
||||
}
|
||||
t.trainingComplete.Store(comp)
|
||||
}
|
||||
t.trainingComplete.Store(comp)
|
||||
|
||||
t.m.Lock()
|
||||
defer t.m.Unlock()
|
||||
@@ -262,7 +340,13 @@ func (t *vectorTrainer) loadTrainedData(bucket *util.BoltBucketImpl) error {
|
||||
|
||||
func (t *vectorTrainer) train(batch *index.Batch) error {
|
||||
// regulate the Train function
|
||||
start := time.Now()
|
||||
t.parent.FireIndexEvent()
|
||||
atomic.AddUint64(&t.parent.stats.TotTrainFireIndexEventTime, uint64(time.Since(start)))
|
||||
atomic.AddUint64(&t.parent.stats.TotTrainFireIndexEvents, 1)
|
||||
if t.trainingComplete.Load() {
|
||||
return fmt.Errorf("training is already complete, cannot accept more training data")
|
||||
}
|
||||
|
||||
var trainData []index.Document
|
||||
for _, doc := range batch.IndexOps {
|
||||
@@ -289,28 +373,69 @@ func (t *vectorTrainer) train(batch *index.Batch) error {
|
||||
sampleSize: len(trainData),
|
||||
ackCh: make(chan error),
|
||||
}
|
||||
// setting the training params using the internal value before the actual
|
||||
// training has started
|
||||
config := t.config
|
||||
if atomic.LoadUint64(&t.trainedSamples) == 0 {
|
||||
trainingParamsBytes := batch.InternalOps[index.TrainingKey]
|
||||
var trainingParams index.TrainingParams
|
||||
if trainingParamsBytes != nil {
|
||||
err = util.UnmarshalJSON(trainingParamsBytes, &trainingParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error parsing training params: %v", err)
|
||||
}
|
||||
trainReq.trainingParams = &trainingParams
|
||||
config = maps.Clone(t.config)
|
||||
config[index.TrainingKey] = &trainingParams
|
||||
}
|
||||
}
|
||||
|
||||
// just builds a new vector index out of the train data provided
|
||||
// this is not necessarily the final train data since this is submitted
|
||||
// as a request to the trainer component to be merged. once the training
|
||||
// is complete, the template will be used for other operations down the line
|
||||
// like merge and search.
|
||||
//
|
||||
// note: this might index text data too, how to handle this? s.segmentConfig?
|
||||
// todo: updates/deletes -> data drift detection
|
||||
if len(trainData) > 0 {
|
||||
trainReq.sample, _, err = t.parent.segPlugin.NewUsing(trainData, t.parent.segmentConfig)
|
||||
trainReq.sample, _, err = t.parent.segPlugin.NewUsing(trainData, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
t.trainCh <- trainReq
|
||||
err = <-trainReq.ackCh
|
||||
if err != nil {
|
||||
if err := t.submit(trainReq); err != nil {
|
||||
return fmt.Errorf("train_vector: train() err'd out with: %w", err)
|
||||
}
|
||||
|
||||
return err
|
||||
return nil
|
||||
}
|
||||
|
||||
// submit hands a request to the trainLoop and waits for its ack. It never
|
||||
// blocks past trainer shutdown: if the trainLoop has already exited (via close,
|
||||
// training completion, or error) the doneCh releases the caller instead of
|
||||
// letting it hang on a request that will never be consumed or acked.
|
||||
func (t *vectorTrainer) submit(req *trainRequest) error {
|
||||
select {
|
||||
case t.trainCh <- req:
|
||||
case <-t.doneCh:
|
||||
return fmt.Errorf("trainer is closed")
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-req.ackCh:
|
||||
return err
|
||||
case <-t.doneCh:
|
||||
// trainLoop acks every request it consumes before returning, so if our
|
||||
// request was processed the ack is already available — prefer it over
|
||||
// reporting a shutdown that didn't actually drop this request.
|
||||
select {
|
||||
case err := <-req.ackCh:
|
||||
return err
|
||||
default:
|
||||
return fmt.Errorf("trainer is closed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *vectorTrainer) getInternal(key []byte) ([]byte, error) {
|
||||
@@ -348,13 +473,20 @@ func (t *vectorTrainer) copyFileLOCKED(file string, d index.IndexDirectory) erro
|
||||
if err != nil {
|
||||
return fmt.Errorf("error updating dest index bolt: %w", err)
|
||||
}
|
||||
|
||||
// update the stats in destination
|
||||
err = d.SetPathInBolt(util.BoltTrainedSamplesKey, binary.LittleEndian.AppendUint64(nil, atomic.LoadUint64(&t.trainedSamples)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("error updating trained samples key: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *vectorTrainer) updateBolt(snapshotsBucket *util.BoltBucketImpl, key []byte, value []byte) error {
|
||||
if bytes.Equal(key, util.BoltTrainerKey) {
|
||||
switch string(key) {
|
||||
case string(util.BoltTrainerKey):
|
||||
trainerBucket, err := snapshotsBucket.CreateBucketIfNotExists(util.BoltTrainerKey)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -377,17 +509,29 @@ func (t *vectorTrainer) updateBolt(snapshotsBucket *util.BoltBucketImpl, key []b
|
||||
return err
|
||||
}
|
||||
|
||||
writerID, err := trainerBucket.Get(util.BoltMetaDataFileWriterIDKey, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error getting writer id: %v", err)
|
||||
}
|
||||
reader, err := util.NewFileReader(string(writerID), nil)
|
||||
reader, err := util.NewFileReader("", nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating file reader: %v", err)
|
||||
}
|
||||
|
||||
// update the centroid index pointer
|
||||
t.trainedIndex, err = t.parent.loadSegment(trainerBucket, reader)
|
||||
// update the centroid index pointer under the write lock; getTrainedIndex
|
||||
// and trainLoop may read t.trainedIndex concurrently.
|
||||
seg, err := t.parent.loadSegment(trainerBucket, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.m.Lock()
|
||||
t.trainedIndex = seg
|
||||
t.m.Unlock()
|
||||
|
||||
case string(util.BoltTrainedSamplesKey):
|
||||
trainedSamples := binary.LittleEndian.Uint64(value)
|
||||
atomic.StoreUint64(&t.trainedSamples, trainedSamples)
|
||||
trainerBucket, err := snapshotsBucket.CreateBucketIfNotExists(util.BoltTrainerKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = trainerBucket.Put(util.BoltTrainedSamplesKey, value, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -395,3 +539,88 @@ func (t *vectorTrainer) updateBolt(snapshotsBucket *util.BoltBucketImpl, key []b
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// dropFileWriterIDs removes the given file writer ids from the trained index.
|
||||
// This is a lifecycle operation (key rotation) that must work for the entire
|
||||
// life of the trained index, not just while training is running.
|
||||
func (t *vectorTrainer) dropFileWriterIDs(ids map[string]struct{}) error {
|
||||
if t.trainingComplete.Load() {
|
||||
if err := t.removeFileWriterIDs(ids); err != nil {
|
||||
return fmt.Errorf("train_vector: dropFileWriterIDs() err'd out with: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
trainReq := &trainRequest{
|
||||
ackCh: make(chan error),
|
||||
removedFileWriterIDs: ids,
|
||||
}
|
||||
if err := t.submit(trainReq); err != nil {
|
||||
return fmt.Errorf("train_vector: dropFileWriterIDs() err'd out with: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *vectorTrainer) removeFileWriterIDs(ids map[string]struct{}) error {
|
||||
// trainer bucket in the bolt file doesn't have any sensitive data to be encrypted,
|
||||
// so we don't have to update it with new writer ids.
|
||||
// invoke the merge API and let the zap side of things handle the update of writer IDs and also
|
||||
// the data in the trained index.
|
||||
t.m.Lock()
|
||||
defer t.m.Unlock()
|
||||
trainedIndexPath := filepath.Join(t.parent.path, index.TrainedIndexFileName)
|
||||
if t.trainedIndex != nil {
|
||||
if encryptedIndex, ok := t.trainedIndex.segment.(segment.SegmentWithCallbacks); ok {
|
||||
if _, ok := ids[encryptedIndex.CallbackId()]; ok {
|
||||
_, _, err := t.parent.segPlugin.MergeUsing([]segment.Segment{t.trainedIndex.segment},
|
||||
[]*roaring.Bitmap{nil}, trainedIndexPath+"temp", t.parent.closeCh, nil, t.config)
|
||||
if err != nil {
|
||||
if serr := os.Remove(trainedIndexPath + "temp"); serr != nil {
|
||||
return fmt.Errorf("error removing temp trained index: %v", serr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
err = t.trainedIndex.segment.Close()
|
||||
if err != nil {
|
||||
if serr := os.Remove(trainedIndexPath + "temp"); serr != nil {
|
||||
return fmt.Errorf("error removing temp trained index: %v", serr)
|
||||
}
|
||||
t.trainedIndex = nil
|
||||
return err
|
||||
}
|
||||
|
||||
if err := moveFile(trainedIndexPath+"temp", trainedIndexPath); err != nil {
|
||||
if serr := os.Remove(trainedIndexPath + "temp"); serr != nil {
|
||||
return fmt.Errorf("error removing temp trained index: %v", serr)
|
||||
}
|
||||
t.trainedIndex = nil
|
||||
return err
|
||||
}
|
||||
|
||||
trainedIndex, err := t.parent.segPlugin.OpenUsing(trainedIndexPath, t.config)
|
||||
if err != nil {
|
||||
t.trainedIndex = nil
|
||||
return err
|
||||
}
|
||||
|
||||
t.trainedIndex = &SegmentSnapshot{segment: trainedIndex}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *vectorTrainer) fileWriterIDsInUse() (map[string]struct{}, error) {
|
||||
t.m.RLock()
|
||||
defer t.m.RUnlock()
|
||||
writerIDs := make(map[string]struct{})
|
||||
if t.trainedIndex != nil {
|
||||
if seg, ok := t.trainedIndex.segment.(segment.SegmentWithCallbacks); ok {
|
||||
writerIDs[seg.CallbackId()] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
return writerIDs, nil
|
||||
}
|
||||
+10
@@ -168,6 +168,16 @@ func (i *unadornedPostingsIterator1Hit) BytesWritten() uint64 {
|
||||
|
||||
func (i *unadornedPostingsIterator1Hit) ResetBytesRead(uint64) {}
|
||||
|
||||
func (i *unadornedPostingsIterator1Hit) ActualBitmap() *roaring.Bitmap { return nil }
|
||||
|
||||
func (i *unadornedPostingsIterator1Hit) DocNum1Hit() (uint64, bool) {
|
||||
return i.docNumOrig, true
|
||||
}
|
||||
|
||||
// ReplaceActual is a no-op: a 1-hit iterator has no actual bitmap, and callers
|
||||
// only invoke ReplaceActual on iterators whose ActualBitmap is non-nil.
|
||||
func (i *unadornedPostingsIterator1Hit) ReplaceActual(*roaring.Bitmap) {}
|
||||
|
||||
// ResetIterator resets the iterator to the original state.
|
||||
func (i *unadornedPostingsIterator1Hit) ResetIterator() {
|
||||
i.docNum = i.docNumOrig
|
||||
|
||||
+33
-19
@@ -213,9 +213,6 @@ func openIndexUsing(path string, runtimeConfig map[string]interface{}) (rv *inde
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("updated mapping present for unupdatable index")
|
||||
}
|
||||
|
||||
// Load the meta data from bolt so that we can read the current index
|
||||
// mapping to compare with
|
||||
err = ui.OpenMeta()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -225,12 +222,12 @@ func openIndexUsing(path string, runtimeConfig map[string]interface{}) (rv *inde
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(rv *indexImpl) {
|
||||
if !rv.open {
|
||||
rv.i.Close()
|
||||
}
|
||||
}(rv)
|
||||
}
|
||||
defer func(rv *indexImpl) {
|
||||
if !rv.open {
|
||||
rv.i.Close()
|
||||
}
|
||||
}(rv)
|
||||
|
||||
// now load the mapping
|
||||
indexReader, err := rv.i.Reader()
|
||||
@@ -269,7 +266,8 @@ func openIndexUsing(path string, runtimeConfig map[string]interface{}) (rv *inde
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fieldInfo, err := DeletedFields(im, um)
|
||||
var fieldInfo map[string]*index.UpdateFieldInfo
|
||||
fieldInfo, err = DeletedFields(im, um)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -284,11 +282,6 @@ func openIndexUsing(path string, runtimeConfig map[string]interface{}) (rv *inde
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(rv *indexImpl) {
|
||||
if !rv.open {
|
||||
rv.i.Close()
|
||||
}
|
||||
}(rv)
|
||||
}
|
||||
|
||||
// mark the index as open
|
||||
@@ -759,6 +752,9 @@ func (i *indexImpl) SearchInContext(ctx context.Context, req *SearchRequest) (sr
|
||||
ctx = context.WithValue(ctx, search.NestedSearchKey, true)
|
||||
}
|
||||
}
|
||||
// Install here, before presearch and the knn collector, so the counter also
|
||||
// covers presearch and KNN filter searchers, not just the main query's.
|
||||
ctx = search.ContextWithTermSearchersCounter(ctx)
|
||||
// ------------------------------------------------------------------------------------------
|
||||
|
||||
if _, ok := ctx.Value(search.PreSearchKey).(bool); ok {
|
||||
@@ -793,6 +789,19 @@ func (i *indexImpl) SearchInContext(ctx context.Context, req *SearchRequest) (sr
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// score="none" + Size means "return any Size+From matching docs", so the
|
||||
// collector may stop scanning early — provided nothing below depends on
|
||||
// unseen matches (facets, KNN, pagination cursor, nested rollup, field sort).
|
||||
if req.Score == ScoreNone && req.Size > 0 &&
|
||||
len(req.Facets) == 0 &&
|
||||
!requestHasKNN(req) &&
|
||||
req.SearchAfter == nil && !reverseQueryExecution &&
|
||||
len(req.Sort) == 1 && req.Sort[0].RequiresScoring() {
|
||||
if nestedMode, ok := ctx.Value(search.NestedSearchKey).(bool); !ok || !nestedMode {
|
||||
coll.SetEarlyStop(req.Size + req.From)
|
||||
}
|
||||
}
|
||||
|
||||
var knnHits []*search.DocumentMatch
|
||||
var skipKNNCollector bool
|
||||
|
||||
@@ -1043,16 +1052,21 @@ func (i *indexImpl) SearchInContext(ctx context.Context, req *SearchRequest) (sr
|
||||
req.SearchAfter = nil
|
||||
}
|
||||
|
||||
totalRelation := TotalRelationEq
|
||||
if coll.EarlyStopped() {
|
||||
totalRelation = TotalRelationGte
|
||||
}
|
||||
rv := &SearchResult{
|
||||
Status: &SearchStatus{
|
||||
Total: 1,
|
||||
Successful: 1,
|
||||
},
|
||||
Hits: hits,
|
||||
Total: coll.Total(),
|
||||
MaxScore: coll.MaxScore(),
|
||||
Took: searchDuration,
|
||||
Facets: coll.FacetResults(),
|
||||
Hits: hits,
|
||||
Total: coll.Total(),
|
||||
TotalRelation: totalRelation,
|
||||
MaxScore: coll.MaxScore(),
|
||||
Took: searchDuration,
|
||||
Facets: coll.FacetResults(),
|
||||
}
|
||||
|
||||
// rescore if fusion flag is set
|
||||
|
||||
+5
@@ -114,6 +114,11 @@ func openIndexMeta(path string) (*indexMeta, error) {
|
||||
if err != nil {
|
||||
return nil, ErrorIndexMetaCorrupt
|
||||
}
|
||||
} else {
|
||||
fileReader, err = util.NewFileReader("", []byte(indexMetaPath))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
im.fileReader = fileReader
|
||||
|
||||
|
||||
+4
@@ -88,6 +88,10 @@ func NewGeoShapeFieldMapping() *mapping.FieldMapping {
|
||||
return mapping.NewGeoShapeFieldMapping()
|
||||
}
|
||||
|
||||
func NewGeoShapeV2FieldMapping() *mapping.FieldMapping {
|
||||
return mapping.NewGeoShapeV2FieldMapping()
|
||||
}
|
||||
|
||||
func NewIPFieldMapping() *mapping.FieldMapping {
|
||||
return mapping.NewIPFieldMapping()
|
||||
}
|
||||
+8
-1
@@ -104,7 +104,7 @@ func (dm *DocumentMapping) Validate(cache *registry.Cache,
|
||||
|
||||
func validateFieldType(field *FieldMapping) error {
|
||||
switch field.Type {
|
||||
case "text", "datetime", "number", "boolean", "geopoint", "geoshape", "IP":
|
||||
case "text", "datetime", "number", "boolean", "geopoint", "geoshape", "geoshape_v2", "IP":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("field: '%s', unknown field type: '%s'",
|
||||
@@ -557,6 +557,8 @@ func (dm *DocumentMapping) processProperty(property interface{}, path []string,
|
||||
fieldMapping.processGeoPoint(property, pathString, path, indexes, context)
|
||||
case "vector_base64":
|
||||
fieldMapping.processVectorBase64(property, pathString, path, indexes, context)
|
||||
case "geoshape_v2":
|
||||
fieldMapping.processGeoShapeV2(property, pathString, path, context)
|
||||
default:
|
||||
fieldMapping.processString(propertyValueString, pathString, path, indexes, context)
|
||||
}
|
||||
@@ -641,6 +643,8 @@ func (dm *DocumentMapping) processProperty(property interface{}, path []string,
|
||||
fieldMapping.processGeoPoint(property, pathString, path, indexes, context)
|
||||
case "geoshape":
|
||||
fieldMapping.processGeoShape(property, pathString, path, indexes, context)
|
||||
case "geoshape_v2":
|
||||
fieldMapping.processGeoShapeV2(property, pathString, path, context)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -666,6 +670,9 @@ func (dm *DocumentMapping) processProperty(property interface{}, path []string,
|
||||
case "geoshape":
|
||||
fieldMapping.processGeoShape(property, pathString, path, indexes, context)
|
||||
walkDocument = true
|
||||
case "geoshape_v2":
|
||||
fieldMapping.processGeoShapeV2(property, pathString, path, context)
|
||||
walkDocument = true
|
||||
default:
|
||||
walkDocument = true
|
||||
}
|
||||
|
||||
+96
-19
@@ -201,6 +201,18 @@ func NewGeoShapeFieldMapping() *FieldMapping {
|
||||
}
|
||||
}
|
||||
|
||||
// NewGeoShapeV2FieldMapping returns a default field mapping for
|
||||
// geoshapes using the new GeoShapeV2 format
|
||||
func NewGeoShapeV2FieldMapping() *FieldMapping {
|
||||
return &FieldMapping{
|
||||
Type: "geoshape_v2",
|
||||
Store: false,
|
||||
Index: true,
|
||||
IncludeInAll: false,
|
||||
DocValues: false,
|
||||
}
|
||||
}
|
||||
|
||||
// NewIPFieldMapping returns a default field mapping for IP points
|
||||
func NewIPFieldMapping() *FieldMapping {
|
||||
return &FieldMapping{
|
||||
@@ -336,47 +348,112 @@ func (fm *FieldMapping) processIP(ip net.IP, pathString string, path []string, i
|
||||
}
|
||||
}
|
||||
|
||||
// processGeoShape processes a property that might be a GeoJSON
|
||||
// shape and adds the appropriate field to the document.
|
||||
func (fm *FieldMapping) processGeoShape(propertyMightBeGeoShape interface{},
|
||||
pathString string, path []string, indexes []uint64, context *walkContext,
|
||||
) {
|
||||
fm.processGeoShapeInternal(propertyMightBeGeoShape, pathString, path, context,
|
||||
func(fieldName string, shapes []*geojson.GeoShape,
|
||||
options index.FieldIndexingOptions) document.Field {
|
||||
field := document.NewGeometryCollectionFieldFromShapesWithIndexingOptions(
|
||||
fieldName, indexes, shapes, options)
|
||||
if field == nil {
|
||||
// return an untyped nil, so that the caller's nil check works;
|
||||
// returning the nil *GeoShapeField directly would produce a
|
||||
// non-nil document.Field interface wrapping a nil pointer
|
||||
return nil
|
||||
}
|
||||
return field
|
||||
},
|
||||
func(fieldName string, shape *geojson.GeoShape,
|
||||
options index.FieldIndexingOptions) document.Field {
|
||||
field := document.NewGeoShapeFieldFromShapeWithIndexingOptions(
|
||||
fieldName, indexes, shape, options)
|
||||
if field == nil {
|
||||
return nil
|
||||
}
|
||||
return field
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// processGeoShapeV2 processes a property that might be a GeoJSON
|
||||
// shape and adds the appropriate field to the document using the new GeoShapeV2 format.
|
||||
func (fm *FieldMapping) processGeoShapeV2(propertyMightBeGeoShape interface{},
|
||||
pathString string, path []string, context *walkContext,
|
||||
) {
|
||||
fm.processGeoShapeInternal(propertyMightBeGeoShape, pathString, path, context,
|
||||
func(fieldName string, shapes []*geojson.GeoShape,
|
||||
options index.FieldIndexingOptions) document.Field {
|
||||
field := document.NewGeometryCollectionV2FieldFromShapesWithIndexingOptions(
|
||||
fieldName, shapes, options)
|
||||
if field == nil {
|
||||
// return an untyped nil, so that the caller's nil check works;
|
||||
// returning the nil *GeoShapeV2Field directly would produce a
|
||||
// non-nil document.Field interface wrapping a nil pointer
|
||||
return nil
|
||||
}
|
||||
return field
|
||||
},
|
||||
func(fieldName string, shape *geojson.GeoShape,
|
||||
options index.FieldIndexingOptions) document.Field {
|
||||
field := document.NewGeoShapeV2FieldFromShapeWithIndexingOptions(
|
||||
fieldName, shape, options)
|
||||
if field == nil {
|
||||
return nil
|
||||
}
|
||||
return field
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// processGeoShapeInternal is a helper function that processes
|
||||
// a property that might be a GeoJSON shape and adds the appropriate
|
||||
// field to the document. It takes two functions as parameters to handle
|
||||
// the creation of fields for geometry collections and individual shapes.
|
||||
func (fm *FieldMapping) processGeoShapeInternal(
|
||||
propertyMightBeGeoShape interface{},
|
||||
pathString string, path []string, context *walkContext,
|
||||
makeCollection func(fieldName string, shapes []*geojson.GeoShape,
|
||||
options index.FieldIndexingOptions) document.Field,
|
||||
makeShape func(fieldName string, shape *geojson.GeoShape,
|
||||
options index.FieldIndexingOptions) document.Field,
|
||||
) {
|
||||
coordValue, shape, err := geo.ParseGeoShapeField(propertyMightBeGeoShape)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var field document.Field
|
||||
var found bool
|
||||
|
||||
if shape == geo.GeometryCollectionType {
|
||||
geoShapes, found := geo.ExtractGeometryCollection(propertyMightBeGeoShape)
|
||||
var geoShapes []*geojson.GeoShape
|
||||
geoShapes, found = geo.ExtractGeometryCollection(propertyMightBeGeoShape)
|
||||
if found {
|
||||
fieldName := getFieldName(pathString, path, fm)
|
||||
options := fm.Options()
|
||||
field := document.NewGeometryCollectionFieldFromShapesWithIndexingOptions(fieldName,
|
||||
indexes, geoShapes, options)
|
||||
context.doc.AddField(field)
|
||||
|
||||
if !fm.IncludeInAll {
|
||||
context.excludedFromAll = append(context.excludedFromAll, fieldName)
|
||||
}
|
||||
field = makeCollection(fieldName, geoShapes, fm.Options())
|
||||
}
|
||||
} else {
|
||||
var geoShape *geojson.GeoShape
|
||||
var found bool
|
||||
|
||||
if shape == geo.CircleType {
|
||||
geoShape, found = geo.ExtractCircle(propertyMightBeGeoShape)
|
||||
} else {
|
||||
geoShape, found = geo.ExtractGeoShapeCoordinates(coordValue, shape)
|
||||
}
|
||||
|
||||
if found {
|
||||
fieldName := getFieldName(pathString, path, fm)
|
||||
options := fm.Options()
|
||||
field := document.NewGeoShapeFieldFromShapeWithIndexingOptions(fieldName,
|
||||
indexes, geoShape, options)
|
||||
context.doc.AddField(field)
|
||||
field = makeShape(fieldName, geoShape, fm.Options())
|
||||
}
|
||||
}
|
||||
|
||||
if !fm.IncludeInAll {
|
||||
context.excludedFromAll = append(context.excludedFromAll, fieldName)
|
||||
}
|
||||
// field is nil when the constructor failed to encode the shape,
|
||||
// in which case nothing is added to the document
|
||||
if found && field != nil {
|
||||
context.doc.AddField(field)
|
||||
if !fm.IncludeInAll {
|
||||
context.excludedFromAll = append(context.excludedFromAll, field.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+21
-8
@@ -525,6 +525,15 @@ func (ss *SearchStatus) Merge(other *SearchStatus) {
|
||||
}
|
||||
}
|
||||
|
||||
// TotalRelation constants describe the accuracy of SearchResult.Total.
|
||||
const (
|
||||
// TotalRelationEq means Total is an exact count of all matching documents.
|
||||
TotalRelationEq = "eq"
|
||||
// TotalRelationGte means Total is a lower bound: collection stopped before
|
||||
// draining every match, so the true match count is >= Total.
|
||||
TotalRelationGte = "gte"
|
||||
)
|
||||
|
||||
// A SearchResult describes the results of executing
|
||||
// a SearchRequest.
|
||||
//
|
||||
@@ -540,14 +549,15 @@ func (ss *SearchStatus) Merge(other *SearchStatus) {
|
||||
// Took - The time taken to execute the search.
|
||||
// Facets - The facet results for the search.
|
||||
type SearchResult struct {
|
||||
Status *SearchStatus `json:"status"`
|
||||
Request *SearchRequest `json:"request,omitempty"`
|
||||
Hits search.DocumentMatchCollection `json:"hits"`
|
||||
Total uint64 `json:"total_hits"`
|
||||
Cost uint64 `json:"cost"`
|
||||
MaxScore float64 `json:"max_score"`
|
||||
Took time.Duration `json:"took"`
|
||||
Facets search.FacetResults `json:"facets"`
|
||||
Status *SearchStatus `json:"status"`
|
||||
Request *SearchRequest `json:"request,omitempty"`
|
||||
Hits search.DocumentMatchCollection `json:"hits"`
|
||||
Total uint64 `json:"total_hits"`
|
||||
TotalRelation string `json:"total_relation"`
|
||||
Cost uint64 `json:"cost"`
|
||||
MaxScore float64 `json:"max_score"`
|
||||
Took time.Duration `json:"took"`
|
||||
Facets search.FacetResults `json:"facets"`
|
||||
// special fields that are applicable only for search
|
||||
// results that are obtained from a presearch
|
||||
SynonymResult search.FieldTermSynonymMap `json:"synonym_result,omitempty"`
|
||||
@@ -675,6 +685,9 @@ func (sr *SearchResult) Merge(other *SearchResult) {
|
||||
sr.Status.Merge(other.Status)
|
||||
sr.Hits = append(sr.Hits, other.Hits...)
|
||||
sr.Total += other.Total
|
||||
if other.TotalRelation == TotalRelationGte {
|
||||
sr.TotalRelation = TotalRelationGte
|
||||
}
|
||||
sr.Cost += other.Cost
|
||||
if other.MaxScore > sr.MaxScore {
|
||||
sr.MaxScore = other.MaxScore
|
||||
|
||||
+76
-35
@@ -15,85 +15,126 @@
|
||||
package collector
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"sort"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/search"
|
||||
)
|
||||
|
||||
// collectStoreHeap is a min-heap of DocumentMatches where the root (heap[0])
|
||||
// is always the *worst* result (lowest score / highest sort key). Popping the
|
||||
// root discards the worst element, so AddNotExceedingSize keeps the best k
|
||||
// documents at all times.
|
||||
//
|
||||
// Implemented as a ternary heap (3 children per node) instead of the standard
|
||||
// library's binary heap. Height is log₃(n) vs log₂(n), so siftDown is
|
||||
// shallower and fetches more children per cache line.
|
||||
type collectStoreHeap struct {
|
||||
heap search.DocumentMatchCollection
|
||||
compare collectorCompare
|
||||
}
|
||||
|
||||
func newStoreHeap(capacity int, compare collectorCompare) *collectStoreHeap {
|
||||
rv := &collectStoreHeap{
|
||||
return &collectStoreHeap{
|
||||
heap: make(search.DocumentMatchCollection, 0, capacity),
|
||||
compare: compare,
|
||||
}
|
||||
heap.Init(rv)
|
||||
return rv
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) AddNotExceedingSize(doc *search.DocumentMatch,
|
||||
size int) *search.DocumentMatch {
|
||||
c.add(doc)
|
||||
if c.Len() > size {
|
||||
if len(c.heap) > size {
|
||||
return c.removeLast()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) add(doc *search.DocumentMatch) {
|
||||
heap.Push(c, doc)
|
||||
c.heap = append(c.heap, doc)
|
||||
c.siftUp(len(c.heap) - 1)
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) removeLast() *search.DocumentMatch {
|
||||
return heap.Pop(c).(*search.DocumentMatch)
|
||||
n := len(c.heap)
|
||||
c.heap[0], c.heap[n-1] = c.heap[n-1], c.heap[0]
|
||||
result := c.heap[n-1]
|
||||
c.heap = c.heap[:n-1]
|
||||
if len(c.heap) > 0 {
|
||||
c.siftDown(0)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// siftUp restores the heap invariant after appending at index i.
|
||||
// Moves element at i toward the root while it is less than (worse than) its parent.
|
||||
func (c *collectStoreHeap) siftUp(i int) {
|
||||
h := c.heap
|
||||
for i > 0 {
|
||||
parent := (i - 1) / 3
|
||||
if c.compare(h[i], h[parent]) > 0 { // h[i] is worse → should be closer to root
|
||||
h[i], h[parent] = h[parent], h[i]
|
||||
i = parent
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// siftDown restores the heap invariant after replacing the root.
|
||||
// Moves element at i toward the leaves while any child is worse (less) than it.
|
||||
func (c *collectStoreHeap) siftDown(i int) {
|
||||
h := c.heap
|
||||
n := len(h)
|
||||
for {
|
||||
first := 3*i + 1
|
||||
if first >= n {
|
||||
break
|
||||
}
|
||||
// Find the worst (least) child among up to three children.
|
||||
worst := first
|
||||
if s := first + 1; s < n && c.compare(h[s], h[worst]) > 0 {
|
||||
worst = s
|
||||
}
|
||||
if t := first + 2; t < n && c.compare(h[t], h[worst]) > 0 {
|
||||
worst = t
|
||||
}
|
||||
if c.compare(h[worst], h[i]) > 0 { // worst child is worse than current → swap
|
||||
h[i], h[worst] = h[worst], h[i]
|
||||
i = worst
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) Final(skip int, fixup collectorFixup) (search.DocumentMatchCollection, error) {
|
||||
count := c.Len()
|
||||
count := len(c.heap)
|
||||
size := count - skip
|
||||
if size <= 0 {
|
||||
return make(search.DocumentMatchCollection, 0), nil
|
||||
}
|
||||
// Sort in-place so heap[0] = best doc (compare < 0 means "better").
|
||||
// pdqsort (sort.Slice) has much better cache behavior than repeated
|
||||
// removeLast (heapsort) because it accesses the array sequentially,
|
||||
// avoiding the scattered pointer dereferences heapsort pays at each level.
|
||||
sort.Slice(c.heap, func(i, j int) bool {
|
||||
return c.compare(c.heap[i], c.heap[j]) < 0
|
||||
})
|
||||
rv := make(search.DocumentMatchCollection, size)
|
||||
for i := size - 1; i >= 0; i-- {
|
||||
doc := heap.Pop(c).(*search.DocumentMatch)
|
||||
for i := 0; i < size; i++ {
|
||||
doc := c.heap[skip+i]
|
||||
rv[i] = doc
|
||||
err := fixup(doc)
|
||||
if err != nil {
|
||||
if err := fixup(doc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) Internal() search.DocumentMatchCollection {
|
||||
return c.heap
|
||||
}
|
||||
|
||||
// heap interface implementation
|
||||
|
||||
func (c *collectStoreHeap) Len() int {
|
||||
return len(c.heap)
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) Less(i, j int) bool {
|
||||
so := c.compare(c.heap[i], c.heap[j])
|
||||
return -so < 0
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) Swap(i, j int) {
|
||||
c.heap[i], c.heap[j] = c.heap[j], c.heap[i]
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) Push(x interface{}) {
|
||||
c.heap = append(c.heap, x.(*search.DocumentMatch))
|
||||
}
|
||||
|
||||
func (c *collectStoreHeap) Pop() interface{} {
|
||||
var rv *search.DocumentMatch
|
||||
rv, c.heap = c.heap[len(c.heap)-1], c.heap[:len(c.heap)-1]
|
||||
return rv
|
||||
func (c *collectStoreHeap) Internal() search.DocumentMatchCollection {
|
||||
return c.heap
|
||||
}
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
// Copyright (c) 2014 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package collector
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/search"
|
||||
)
|
||||
|
||||
type collectStoreList struct {
|
||||
results *list.List
|
||||
compare collectorCompare
|
||||
}
|
||||
|
||||
func newStoreList(capacity int, compare collectorCompare) *collectStoreList {
|
||||
rv := &collectStoreList{
|
||||
results: list.New(),
|
||||
compare: compare,
|
||||
}
|
||||
|
||||
return rv
|
||||
}
|
||||
|
||||
func (c *collectStoreList) AddNotExceedingSize(doc *search.DocumentMatch, size int) *search.DocumentMatch {
|
||||
c.add(doc)
|
||||
if c.len() > size {
|
||||
return c.removeLast()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *collectStoreList) add(doc *search.DocumentMatch) {
|
||||
for e := c.results.Front(); e != nil; e = e.Next() {
|
||||
curr := e.Value.(*search.DocumentMatch)
|
||||
if c.compare(doc, curr) >= 0 {
|
||||
c.results.InsertBefore(doc, e)
|
||||
return
|
||||
}
|
||||
}
|
||||
// if we got to the end, we still have to add it
|
||||
c.results.PushBack(doc)
|
||||
}
|
||||
|
||||
func (c *collectStoreList) removeLast() *search.DocumentMatch {
|
||||
return c.results.Remove(c.results.Front()).(*search.DocumentMatch)
|
||||
}
|
||||
|
||||
func (c *collectStoreList) Final(skip int, fixup collectorFixup) (search.DocumentMatchCollection, error) {
|
||||
if c.results.Len()-skip > 0 {
|
||||
rv := make(search.DocumentMatchCollection, c.results.Len()-skip)
|
||||
i := 0
|
||||
skipped := 0
|
||||
for e := c.results.Back(); e != nil; e = e.Prev() {
|
||||
if skipped < skip {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
rv[i] = e.Value.(*search.DocumentMatch)
|
||||
err := fixup(rv[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i++
|
||||
}
|
||||
return rv, nil
|
||||
}
|
||||
return search.DocumentMatchCollection{}, nil
|
||||
}
|
||||
|
||||
func (c *collectStoreList) Internal() search.DocumentMatchCollection {
|
||||
rv := make(search.DocumentMatchCollection, c.results.Len())
|
||||
i := 0
|
||||
for e := c.results.Front(); e != nil; e = e.Next() {
|
||||
rv[i] = e.Value.(*search.DocumentMatch)
|
||||
i++
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
func (c *collectStoreList) len() int {
|
||||
return c.results.Len()
|
||||
}
|
||||
+124
-73
@@ -66,6 +66,7 @@ type TopNCollector struct {
|
||||
facetsBuilder *search.FacetsBuilder
|
||||
|
||||
store collectorStore
|
||||
cmp collectorCompare // specialized or generic; shared by heap + dmHandler
|
||||
|
||||
needDocIds bool
|
||||
neededFields []string
|
||||
@@ -81,6 +82,11 @@ type TopNCollector struct {
|
||||
hybridMergeCallback search.HybridMergeCallbackFn
|
||||
|
||||
nestedStore *collectStoreNested
|
||||
|
||||
fastPrepare bool
|
||||
|
||||
earlyStopN int
|
||||
earlyStopped bool
|
||||
}
|
||||
|
||||
// CheckDoneEvery controls how frequently we check the context deadline
|
||||
@@ -125,11 +131,18 @@ func NewNestedTopNCollectorAfter(size int, sort search.SortOrder, after []string
|
||||
}
|
||||
|
||||
func newTopNCollector(size int, skip int, sort search.SortOrder, nr index.NestedReader) *TopNCollector {
|
||||
hc := &TopNCollector{size: size, skip: skip, sort: sort}
|
||||
hc := &TopNCollector{
|
||||
size: size,
|
||||
skip: skip,
|
||||
sort: sort,
|
||||
neededFields: sort.RequiredFields(),
|
||||
cachedScoring: sort.CacheIsScore(),
|
||||
cachedDesc: sort.CacheDescending(),
|
||||
needDocIds: sort.RequiresDocID(),
|
||||
}
|
||||
|
||||
hc.store = getOptimalCollectorStore(size, skip, func(i, j *search.DocumentMatch) int {
|
||||
return hc.sort.Compare(hc.cachedScoring, hc.cachedDesc, i, j)
|
||||
})
|
||||
hc.cmp = getOptimalCollectorCompare(hc)
|
||||
hc.store = getOptimalCollectorStore(size, skip, hc.cmp)
|
||||
|
||||
if nr != nil {
|
||||
descAdder := func(parent, child *search.DocumentMatch) error {
|
||||
@@ -158,17 +171,18 @@ func newTopNCollector(size int, skip int, sort search.SortOrder, nr index.Nested
|
||||
hc.nestedStore = newStoreNested(nr, search.DescendantAdderCallbackFn(descAdder))
|
||||
}
|
||||
|
||||
// these lookups traverse an interface, so do once up-front
|
||||
if sort.RequiresDocID() {
|
||||
hc.needDocIds = true
|
||||
}
|
||||
hc.neededFields = sort.RequiredFields()
|
||||
hc.cachedScoring = sort.CacheIsScore()
|
||||
hc.cachedDesc = sort.CacheDescending()
|
||||
|
||||
return hc
|
||||
}
|
||||
|
||||
func getOptimalCollectorCompare(hc *TopNCollector) collectorCompare {
|
||||
if len(hc.sort) == 1 && hc.cachedScoring[0] && hc.cachedDesc[0] {
|
||||
return search.CompareScoreDescending
|
||||
}
|
||||
return func(i, j *search.DocumentMatch) int {
|
||||
return hc.sort.Compare(hc.cachedScoring, hc.cachedDesc, i, j)
|
||||
}
|
||||
}
|
||||
|
||||
// Creates a dummy document to compare with for pagination.
|
||||
func createSearchAfterDocument(sort search.SortOrder, after []string) *search.DocumentMatch {
|
||||
encodedAfter := make([]string, len(after))
|
||||
@@ -327,6 +341,11 @@ func (hc *TopNCollector) Collect(ctx context.Context, searcher search.Searcher,
|
||||
}
|
||||
|
||||
hc.needDocIds = hc.needDocIds || loadID
|
||||
|
||||
// fastPrepare is set to true when a hit needs only basicPrepare plus the shared
|
||||
// score sort value (see canFastPrepare). Applies only to score-sorted queries
|
||||
// with no field-loading needs.
|
||||
hc.fastPrepare = hc.canFastPrepare()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
search.RecordSearchCost(ctx, search.AbortM, 0)
|
||||
@@ -361,18 +380,29 @@ func (hc *TopNCollector) Collect(ctx context.Context, searcher search.Searcher,
|
||||
}
|
||||
}
|
||||
if next != nil {
|
||||
err = hc.adjustDocumentMatch(searchContext, reader, next)
|
||||
if err != nil {
|
||||
break
|
||||
if hc.knnHits != nil {
|
||||
err = hc.adjustKNNDocumentMatch(searchContext, reader, next)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
err = hc.prepareDocumentMatch(searchContext, reader, next, false)
|
||||
if err != nil {
|
||||
break
|
||||
hc.basicPrepare(next)
|
||||
if hc.fastPrepare {
|
||||
next.Sort = sortByScoreOpt
|
||||
} else {
|
||||
err = hc.prepareDocumentMatch(searchContext, reader, next)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
err = dmHandler(next)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if hc.earlyStopN > 0 && hc.total >= uint64(hc.earlyStopN) {
|
||||
hc.earlyStopped = true
|
||||
break
|
||||
}
|
||||
}
|
||||
next, err = searcher.Next(searchContext)
|
||||
}
|
||||
@@ -385,14 +415,21 @@ func (hc *TopNCollector) Collect(ctx context.Context, searcher search.Searcher,
|
||||
if hc.nestedStore != nil {
|
||||
currRoot := hc.nestedStore.Current()
|
||||
if currRoot != nil {
|
||||
err = hc.adjustDocumentMatch(searchContext, reader, currRoot)
|
||||
if err != nil {
|
||||
return err
|
||||
if hc.knnHits != nil {
|
||||
err = hc.adjustKNNDocumentMatch(searchContext, reader, currRoot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// no descendants at this point
|
||||
err = hc.prepareDocumentMatch(searchContext, reader, currRoot, false)
|
||||
if err != nil {
|
||||
return err
|
||||
hc.basicPrepare(currRoot)
|
||||
if hc.fastPrepare {
|
||||
currRoot.Sort = sortByScoreOpt
|
||||
} else {
|
||||
err = hc.prepareDocumentMatch(searchContext, reader, currRoot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = dmHandler(currRoot)
|
||||
@@ -406,7 +443,7 @@ func (hc *TopNCollector) Collect(ctx context.Context, searcher search.Searcher,
|
||||
// we may have some knn hits left that did not match any of the top N tf-idf hits
|
||||
// we need to add them to the collector store to consider them as well.
|
||||
for _, knnDoc := range hc.knnHits {
|
||||
err = hc.prepareDocumentMatch(searchContext, reader, knnDoc, true)
|
||||
err = hc.prepareKNNDocumentMatch(searchContext, reader, knnDoc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -447,60 +484,45 @@ func (hc *TopNCollector) Collect(ctx context.Context, searcher search.Searcher,
|
||||
|
||||
var sortByScoreOpt = []string{"_score"}
|
||||
|
||||
func (hc *TopNCollector) adjustDocumentMatch(ctx *search.SearchContext,
|
||||
func (hc *TopNCollector) adjustKNNDocumentMatch(ctx *search.SearchContext,
|
||||
reader index.IndexReader, d *search.DocumentMatch) (err error) {
|
||||
if hc.knnHits != nil {
|
||||
d.ID, err = reader.ExternalID(d.IndexInternalID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if knnHit, ok := hc.knnHits[d.ID]; ok {
|
||||
// we have a knn hit corresponding to this document
|
||||
hc.hybridMergeCallback(d, knnHit)
|
||||
// remove this knn hit from the map as it's already
|
||||
// been merged
|
||||
delete(hc.knnHits, d.ID)
|
||||
}
|
||||
d.ID, err = reader.ExternalID(d.IndexInternalID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if knnHit, ok := hc.knnHits[d.ID]; ok {
|
||||
// merge this document's hit with its knn score, expl etc. and remove it from the map
|
||||
hc.hybridMergeCallback(d, knnHit)
|
||||
delete(hc.knnHits, d.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hc *TopNCollector) basicPrepare(d *search.DocumentMatch) {
|
||||
hc.total++
|
||||
d.HitNumber = hc.total
|
||||
if d.Score > hc.maxScore {
|
||||
hc.maxScore = d.Score
|
||||
}
|
||||
}
|
||||
|
||||
func (hc *TopNCollector) canFastPrepare() bool {
|
||||
return len(hc.neededFields) == 0 && !hc.needDocIds &&
|
||||
len(hc.sort) == 1 && hc.cachedScoring[0]
|
||||
}
|
||||
|
||||
// prepareDocumentMatch does the non-fast preparation for a regular (non-KNN)
|
||||
// hit: visiting field terms required for sort/facets, loading the docID if
|
||||
// needed, and computing the sort value. basicPrepare must be called first.
|
||||
func (hc *TopNCollector) prepareDocumentMatch(ctx *search.SearchContext,
|
||||
reader index.IndexReader, d *search.DocumentMatch, isKnnDoc bool) (err error) {
|
||||
reader index.IndexReader, d *search.DocumentMatch) (err error) {
|
||||
|
||||
// visit field terms for features that require it (sort, facets)
|
||||
if !isKnnDoc && len(hc.neededFields) > 0 {
|
||||
if len(hc.neededFields) > 0 {
|
||||
err = hc.visitFieldTerms(reader, d, hc.updateFieldVisitor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if isKnnDoc && hc.facetsBuilder != nil {
|
||||
// we need to visit the field terms for the knn document
|
||||
// only for those fields that are required for faceting
|
||||
// and not for sorting. This is because the knn document's
|
||||
// sort value is already computed in the knn collector.
|
||||
err = hc.visitFieldTerms(reader, d, func(field string, term []byte) {
|
||||
if hc.facetsBuilder != nil {
|
||||
hc.facetsBuilder.UpdateVisitor(field, term)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// increment total hits
|
||||
hc.total++
|
||||
d.HitNumber = hc.total
|
||||
|
||||
// update max score
|
||||
if d.Score > hc.maxScore {
|
||||
hc.maxScore = d.Score
|
||||
}
|
||||
// early exit as the document match had its sort value calculated in the knn
|
||||
// collector itself
|
||||
if isKnnDoc {
|
||||
return nil
|
||||
}
|
||||
|
||||
// see if we need to load ID (at this early stage, for example to sort on it)
|
||||
@@ -521,6 +543,25 @@ func (hc *TopNCollector) prepareDocumentMatch(ctx *search.SearchContext,
|
||||
return nil
|
||||
}
|
||||
|
||||
// prepareKNNDocumentMatch prepares a KNN hit. Its sort value was already
|
||||
// computed by the KNN collector, so only facet field visiting (if any) and the
|
||||
// basic bookkeeping are needed.
|
||||
func (hc *TopNCollector) prepareKNNDocumentMatch(ctx *search.SearchContext,
|
||||
reader index.IndexReader, d *search.DocumentMatch) (err error) {
|
||||
|
||||
if hc.facetsBuilder != nil {
|
||||
err = hc.visitFieldTerms(reader, d, func(field string, term []byte) {
|
||||
hc.facetsBuilder.UpdateVisitor(field, term)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
hc.basicPrepare(d)
|
||||
return nil
|
||||
}
|
||||
|
||||
func MakeTopNDocumentMatchHandler(
|
||||
ctx *search.SearchContext) (search.DocumentMatchHandler, bool, error) {
|
||||
var hc *TopNCollector
|
||||
@@ -538,7 +579,7 @@ func MakeTopNDocumentMatchHandler(
|
||||
// exact sort order matches use hit number to break tie
|
||||
// but we want to allow for exact match, so we pretend
|
||||
hc.searchAfter.HitNumber = d.HitNumber
|
||||
if hc.sort.Compare(hc.cachedScoring, hc.cachedDesc, d, hc.searchAfter) <= 0 {
|
||||
if hc.cmp(d, hc.searchAfter) <= 0 {
|
||||
ctx.DocumentMatchPool.Put(d)
|
||||
return nil
|
||||
}
|
||||
@@ -548,9 +589,7 @@ func MakeTopNDocumentMatchHandler(
|
||||
// with this one comparison, we can avoid all heap operations if
|
||||
// this hit would have been added and then immediately removed
|
||||
if hc.lowestMatchOutsideResults != nil {
|
||||
cmp := hc.sort.Compare(hc.cachedScoring, hc.cachedDesc, d,
|
||||
hc.lowestMatchOutsideResults)
|
||||
if cmp >= 0 {
|
||||
if hc.cmp(d, hc.lowestMatchOutsideResults) >= 0 {
|
||||
// this hit can't possibly be in the result set, so avoid heap ops
|
||||
ctx.DocumentMatchPool.Put(d)
|
||||
return nil
|
||||
@@ -562,8 +601,7 @@ func MakeTopNDocumentMatchHandler(
|
||||
if hc.lowestMatchOutsideResults == nil {
|
||||
hc.lowestMatchOutsideResults = removed
|
||||
} else {
|
||||
cmp := hc.sort.Compare(hc.cachedScoring, hc.cachedDesc,
|
||||
removed, hc.lowestMatchOutsideResults)
|
||||
cmp := hc.cmp(removed, hc.lowestMatchOutsideResults)
|
||||
if cmp < 0 {
|
||||
tmp := hc.lowestMatchOutsideResults
|
||||
hc.lowestMatchOutsideResults = removed
|
||||
@@ -661,6 +699,19 @@ func (hc *TopNCollector) Total() uint64 {
|
||||
return hc.total
|
||||
}
|
||||
|
||||
// SetEarlyStop makes Collect() stop pulling from the searcher once n hits have
|
||||
// been collected; n <= 0 disables. Callers must ensure unseen docs cannot
|
||||
// change the result.
|
||||
func (hc *TopNCollector) SetEarlyStop(n int) {
|
||||
hc.earlyStopN = n
|
||||
}
|
||||
|
||||
// EarlyStopped reports whether Collect() stopped early; if true, Total() is a
|
||||
// lower bound.
|
||||
func (hc *TopNCollector) EarlyStopped() bool {
|
||||
return hc.earlyStopped
|
||||
}
|
||||
|
||||
// MaxScore returns the maximum score seen across all the hits
|
||||
func (hc *TopNCollector) MaxScore() float64 {
|
||||
return hc.maxScore
|
||||
|
||||
+10
-3
@@ -76,13 +76,20 @@ func (q *CustomFilterQuery) Searcher(ctx context.Context, i index.IndexReader, m
|
||||
var dvReader index.DocValueReader
|
||||
var fieldTypes map[string]string
|
||||
if len(q.Fields) > 0 {
|
||||
var err2 error
|
||||
dvReader, err2 = i.DocValueReader(q.Fields)
|
||||
// Expand a "*" wildcard to the concrete field set; the doc-value
|
||||
// reader matches field names literally and would otherwise load
|
||||
// nothing, leaving d.Fields empty in the callback.
|
||||
fields, err2 := expandFieldWildcard(q.Fields, i)
|
||||
if err2 != nil {
|
||||
_ = childSearcher.Close()
|
||||
return nil, err2
|
||||
}
|
||||
fieldTypes = resolveFieldTypes(q.Fields, m)
|
||||
dvReader, err2 = i.DocValueReader(fields)
|
||||
if err2 != nil {
|
||||
_ = childSearcher.Close()
|
||||
return nil, err2
|
||||
}
|
||||
fieldTypes = resolveFieldTypes(fields, m)
|
||||
}
|
||||
|
||||
return searcher.NewCustomFilterSearcher(ctx, childSearcher, q.filterFunc, dvReader, i, fieldTypes), nil
|
||||
|
||||
+40
@@ -20,6 +20,7 @@ import (
|
||||
|
||||
"github.com/blevesearch/bleve/v2/mapping"
|
||||
"github.com/blevesearch/bleve/v2/util"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
)
|
||||
|
||||
func unmarshalCustomQueryPayload(data []byte, key string) (Query, []string, map[string]interface{}, error) {
|
||||
@@ -94,3 +95,42 @@ func resolveFieldTypes(fields []string, m mapping.IndexMapping) map[string]strin
|
||||
}
|
||||
return types
|
||||
}
|
||||
|
||||
// expandFieldWildcard replaces a "*" entry in the requested fields with the
|
||||
// concrete set of fields in the index, mirroring how the standard stored-field
|
||||
// loader treats "*" (see LoadAndHighlightFields). Custom-query callbacks read
|
||||
// field values via the doc-value reader, which matches field names literally
|
||||
// and has no wildcard handling of its own; without this expansion a request for
|
||||
// fields:["*"] resolves to a single field literally named "*", matches nothing,
|
||||
// and leaves d.Fields empty in the callback.
|
||||
//
|
||||
// The internal composite/identifier fields ("_all", "_id") are excluded so the
|
||||
// callback sees the same fields the stored-field "*" path would surface rather
|
||||
// than the tokenized _all blob or the document id (already available as the
|
||||
// hit's ID). When fields does not contain "*", it is returned unchanged.
|
||||
func expandFieldWildcard(fields []string, i index.IndexReader) ([]string, error) {
|
||||
hasWildcard := false
|
||||
for _, f := range fields {
|
||||
if f == "*" {
|
||||
hasWildcard = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasWildcard {
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
allFields, err := i.Fields()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
expanded := make([]string, 0, len(allFields))
|
||||
for _, f := range allFields {
|
||||
if f == "_all" || f == "_id" {
|
||||
continue
|
||||
}
|
||||
expanded = append(expanded, f)
|
||||
}
|
||||
return expanded, nil
|
||||
}
|
||||
+11
-4
@@ -76,16 +76,23 @@ func (q *CustomScoreQuery) Searcher(ctx context.Context, i index.IndexReader, m
|
||||
var dvReader index.DocValueReader
|
||||
var fieldTypes map[string]string
|
||||
if len(q.Fields) > 0 {
|
||||
var err2 error
|
||||
dvReader, err2 = i.DocValueReader(q.Fields)
|
||||
// Expand a "*" wildcard to the concrete field set; the doc-value
|
||||
// reader matches field names literally and would otherwise load
|
||||
// nothing, leaving d.Fields empty in the callback.
|
||||
fields, err2 := expandFieldWildcard(q.Fields, i)
|
||||
if err2 != nil {
|
||||
_ = childSearcher.Close()
|
||||
return nil, err2
|
||||
}
|
||||
fieldTypes = resolveFieldTypes(q.Fields, m)
|
||||
dvReader, err2 = i.DocValueReader(fields)
|
||||
if err2 != nil {
|
||||
_ = childSearcher.Close()
|
||||
return nil, err2
|
||||
}
|
||||
fieldTypes = resolveFieldTypes(fields, m)
|
||||
}
|
||||
|
||||
return searcher.NewCustomScoreSearcher(ctx, childSearcher, q.scoreFunc, dvReader, i, fieldTypes), nil
|
||||
return searcher.NewCustomScoreSearcher(ctx, childSearcher, q.scoreFunc, dvReader, i, fieldTypes, options.Explain), nil
|
||||
}
|
||||
|
||||
func (q *CustomScoreQuery) Validate() error {
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/geo"
|
||||
"github.com/blevesearch/bleve/v2/mapping"
|
||||
"github.com/blevesearch/bleve/v2/search"
|
||||
"github.com/blevesearch/bleve/v2/search/searcher"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
)
|
||||
|
||||
type GeoShapeV2Query struct {
|
||||
GeometryV2 Geometry `json:"geometry_v2,omitempty"`
|
||||
FieldVal string `json:"field,omitempty"`
|
||||
BoostVal *Boost `json:"boost,omitempty"`
|
||||
}
|
||||
|
||||
func NewGeoShapeV2Query(coordinates [][][][]float64, typ,
|
||||
relation string) (*GeoShapeV2Query, error) {
|
||||
s, _, err := geo.NewGeoJsonShape(coordinates, typ)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &GeoShapeV2Query{GeometryV2: Geometry{Shape: s,
|
||||
Relation: relation}}, nil
|
||||
}
|
||||
|
||||
func NewGeoShapeV2CircleQuery(center []float64, radius,
|
||||
relation string) (*GeoShapeV2Query, error) {
|
||||
s, _, err := geo.NewGeoCircleShape(center, radius)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &GeoShapeV2Query{GeometryV2: Geometry{Shape: s,
|
||||
Relation: relation}}, nil
|
||||
}
|
||||
|
||||
func NewGeoShapeV2GeometryCollectionQuery(coordinates [][][][][]float64,
|
||||
types []string, relation string) (*GeoShapeV2Query, error) {
|
||||
s, _, err := geo.NewGeometryCollection(coordinates, types)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &GeoShapeV2Query{GeometryV2: Geometry{Shape: s,
|
||||
Relation: relation}}, nil
|
||||
}
|
||||
|
||||
func (q *GeoShapeV2Query) Boost() float64 {
|
||||
return q.BoostVal.Value()
|
||||
}
|
||||
|
||||
func (q *GeoShapeV2Query) SetBoost(b float64) {
|
||||
boost := Boost(b)
|
||||
q.BoostVal = &boost
|
||||
}
|
||||
|
||||
func (q *GeoShapeV2Query) Field() string {
|
||||
return q.FieldVal
|
||||
}
|
||||
|
||||
func (q *GeoShapeV2Query) SetField(f string) {
|
||||
q.FieldVal = f
|
||||
}
|
||||
|
||||
func (q *GeoShapeV2Query) Validate() error {
|
||||
switch q.GeometryV2.Relation {
|
||||
case "intersects", "contains", "within", "disjoint":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("invalid relation: %q for geoshape_v2 query, "+
|
||||
"valid relations are: intersects, contains, within, disjoint",
|
||||
q.GeometryV2.Relation)
|
||||
}
|
||||
}
|
||||
|
||||
func (q *GeoShapeV2Query) Searcher(ctx context.Context,
|
||||
i index.IndexReader, m mapping.IndexMapping,
|
||||
options search.SearcherOptions) (search.Searcher, error) {
|
||||
field := q.FieldVal
|
||||
if q.FieldVal == "" {
|
||||
field = m.DefaultSearchField()
|
||||
}
|
||||
|
||||
ctx = context.WithValue(ctx, search.QueryTypeKey, search.Geo)
|
||||
|
||||
return searcher.NewGeoShapeV2Searcher(ctx, i, q.GeometryV2.Shape,
|
||||
q.GeometryV2.Relation, field, q.BoostVal.Value(), options)
|
||||
}
|
||||
+10
@@ -379,6 +379,16 @@ func ParseQuery(input []byte) (Query, error) {
|
||||
return &rv, nil
|
||||
}
|
||||
|
||||
_, hasGeo = tmp["geometry_v2"]
|
||||
if hasGeo {
|
||||
var rv GeoShapeV2Query
|
||||
err := util.UnmarshalJSON(input, &rv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &rv, nil
|
||||
}
|
||||
|
||||
_, hasCIDR := tmp["cidr"]
|
||||
if hasCIDR {
|
||||
var rv IPRangeQuery
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ func (s *ConstantScorer) Score(ctx *search.SearchContext, id index.IndexInternal
|
||||
var scoreExplanation *search.Explanation
|
||||
|
||||
rv := ctx.DocumentMatchPool.Get()
|
||||
rv.IndexInternalID = id
|
||||
rv.IndexInternalID = index.NewIndexInternalIDFrom(rv.IndexInternalID, id)
|
||||
|
||||
if s.includeScore {
|
||||
score := s.constant
|
||||
|
||||
+17
-16
@@ -222,39 +222,40 @@ OUTER:
|
||||
|
||||
// Reset allows an already allocated DocumentMatch to be reused
|
||||
func (dm *DocumentMatch) Reset() *DocumentMatch {
|
||||
// remember the []byte used for the IndexInternalID
|
||||
// Save backing arrays for reuse — these are restored below.
|
||||
indexInternalID := dm.IndexInternalID
|
||||
// remember the []interface{} used for sort
|
||||
sort := dm.Sort
|
||||
// remember the []string used for decoded sort
|
||||
sortBuf := dm.Sort
|
||||
decodedSort := dm.DecodedSort
|
||||
// remember the FieldTermLocations backing array
|
||||
ftls := dm.FieldTermLocations
|
||||
for i := range ftls { // recycle the ArrayPositions of each location
|
||||
ftls[i].Location.ArrayPositions = ftls[i].Location.ArrayPositions[:0]
|
||||
}
|
||||
// remember the score breakdown map
|
||||
scoreBreakdown := dm.ScoreBreakdown
|
||||
// clear out the score breakdown map
|
||||
clear(scoreBreakdown)
|
||||
if scoreBreakdown != nil {
|
||||
clear(scoreBreakdown)
|
||||
}
|
||||
// remember the Descendants backing array
|
||||
descendants := dm.Descendants
|
||||
for i := range descendants { // recycle each IndexInternalID
|
||||
descendants[i] = descendants[i][:0]
|
||||
}
|
||||
// idiom to copy over from empty DocumentMatch (0 allocations)
|
||||
*dm = DocumentMatch{}
|
||||
// reuse the []byte already allocated (and reset len to 0)
|
||||
// Zero only the fields that are not restored below.
|
||||
dm.Index = ""
|
||||
dm.ID = ""
|
||||
dm.Score = 0
|
||||
dm.Expl = nil
|
||||
dm.Locations = nil
|
||||
dm.Fragments = nil
|
||||
dm.Fields = nil
|
||||
dm.HitNumber = 0
|
||||
dm.IndexNames = nil
|
||||
// Restore reusable allocations.
|
||||
dm.IndexInternalID = indexInternalID[:0]
|
||||
// reuse the []interface{} already allocated (and reset len to 0)
|
||||
dm.Sort = sort[:0]
|
||||
// reuse the []string already allocated (and reset len to 0)
|
||||
dm.Sort = sortBuf[:0]
|
||||
dm.DecodedSort = decodedSort[:0]
|
||||
// reuse the FieldTermLocations already allocated (and reset len to 0)
|
||||
dm.FieldTermLocations = ftls[:0]
|
||||
// reuse the Descendants already allocated (and reset len to 0)
|
||||
dm.Descendants = descendants[:0]
|
||||
// reuse the score breakdown map already allocated (after clearing it)
|
||||
dm.ScoreBreakdown = scoreBreakdown
|
||||
return dm
|
||||
}
|
||||
|
||||
+34
-18
@@ -22,43 +22,59 @@ import (
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
)
|
||||
|
||||
// loadDocValuesOnHit uses the supplied DocValueReader to visit doc values
|
||||
// for the given hit and populate hit.Fields. It also resolves hit.ID if empty.
|
||||
// It is a no-op when dvReader is nil.
|
||||
// loadDocValuesOnHitWithTypes resolves hit.ID and returns the hit's doc-value
|
||||
// fields in a new map. It does not touch hit.Fields, so these UDF-input fields
|
||||
// can't leak into SearchRequest.Fields; the caller owns the map. Returns nil
|
||||
// when dvReader is nil.
|
||||
//
|
||||
// fieldTypes maps field name → mapping type (e.g. "datetime", "number").
|
||||
// When provided, datetime fields are decoded from their stored nanosecond
|
||||
// int64 into an RFC3339Nano string, while numeric fields use IEEE 754 bit
|
||||
// reinterpretation to recover the original float64. When nil, all prefix-coded
|
||||
// values use the numeric (float64) path.
|
||||
func loadDocValuesOnHit(hit *search.DocumentMatch, dvReader index.DocValueReader,
|
||||
r index.IndexReader) error {
|
||||
return loadDocValuesOnHitWithTypes(hit, dvReader, r, nil)
|
||||
}
|
||||
|
||||
// fieldTypes maps a field name to its type: datetime fields decode to an
|
||||
// RFC3339Nano string, numeric fields to float64. nil treats all prefix-coded
|
||||
// values as numeric.
|
||||
func loadDocValuesOnHitWithTypes(hit *search.DocumentMatch, dvReader index.DocValueReader,
|
||||
r index.IndexReader, fieldTypes map[string]string) error {
|
||||
r index.IndexReader, fieldTypes map[string]string) (map[string]interface{}, error) {
|
||||
// Always resolve external ID so the callback can read hit.ID.
|
||||
if hit.ID == "" && r != nil {
|
||||
extID, err := r.ExternalID(hit.IndexInternalID)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
hit.ID = extID
|
||||
}
|
||||
|
||||
if dvReader == nil {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := make(map[string]interface{})
|
||||
err := dvReader.VisitDocValues(hit.IndexInternalID, func(field string, term []byte) {
|
||||
value := decodeDocValueTerm(term, fieldTypes[field])
|
||||
if value != nil {
|
||||
hit.AddFieldValue(field, value)
|
||||
addFieldValueToMap(fields, field, value)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return err
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// addFieldValueToMap adds value under name, mirroring DocumentMatch.AddFieldValue:
|
||||
// a repeated field name accumulates into a []interface{} slice.
|
||||
func addFieldValueToMap(fields map[string]interface{}, name string, value interface{}) {
|
||||
existingVal, ok := fields[name]
|
||||
if !ok {
|
||||
fields[name] = value
|
||||
return
|
||||
}
|
||||
|
||||
valSlice, ok := existingVal.([]interface{})
|
||||
if ok {
|
||||
valSlice = append(valSlice, value)
|
||||
} else {
|
||||
valSlice = []interface{}{existingVal, value}
|
||||
}
|
||||
fields[name] = valSlice
|
||||
}
|
||||
|
||||
// decodeDocValueTerm converts raw doc value bytes into a typed Go value.
|
||||
|
||||
+34
-9
@@ -31,15 +31,18 @@ func init() {
|
||||
}
|
||||
|
||||
// CustomFilterFunc decides whether a hit (with doc-value fields populated)
|
||||
// should be kept. Unlike FilterFunc it does not receive a SearchContext since
|
||||
// custom-query callbacks only need the DocumentMatch.
|
||||
type CustomFilterFunc func(d *search.DocumentMatch) bool
|
||||
// should be kept. It receives the search's context so a long-running callback
|
||||
// (e.g. a JS UDF) can honor the query deadline/cancellation. A non-nil error
|
||||
// aborts the search so the failure can be surfaced to the caller rather than
|
||||
// silently dropping the hit.
|
||||
type CustomFilterFunc func(ctx context.Context, d *search.DocumentMatch) (bool, error)
|
||||
|
||||
// CustomFilterSearcher wraps a child searcher, optionally loads doc values
|
||||
// into each DocumentMatch, then applies a CustomFilterFunc to decide whether
|
||||
// to keep the hit. Unlike FilteringSearcher this variant is purpose-built for
|
||||
// custom queries that need field values at callback time.
|
||||
type CustomFilterSearcher struct {
|
||||
ctx context.Context
|
||||
child search.Searcher
|
||||
accept CustomFilterFunc
|
||||
dvReader index.DocValueReader
|
||||
@@ -52,6 +55,7 @@ func NewCustomFilterSearcher(ctx context.Context, child search.Searcher,
|
||||
indexReader index.IndexReader,
|
||||
fieldTypes map[string]string) *CustomFilterSearcher {
|
||||
return &CustomFilterSearcher{
|
||||
ctx: ctx,
|
||||
child: child,
|
||||
accept: filter,
|
||||
dvReader: dvReader,
|
||||
@@ -68,12 +72,23 @@ func (f *CustomFilterSearcher) Size() int {
|
||||
func (f *CustomFilterSearcher) Next(ctx *search.SearchContext) (*search.DocumentMatch, error) {
|
||||
next, err := f.child.Next(ctx)
|
||||
for next != nil && err == nil {
|
||||
if err = loadDocValuesOnHitWithTypes(next, f.dvReader, f.indexReader, f.fieldTypes); err != nil {
|
||||
return nil, err
|
||||
// Put the loaded fields on the hit only for the callback, so UDF-input
|
||||
// fields don't override SearchRequest.Fields in the response.
|
||||
udfFields, lerr := loadDocValuesOnHitWithTypes(next, f.dvReader, f.indexReader, f.fieldTypes)
|
||||
if lerr != nil {
|
||||
return nil, lerr
|
||||
}
|
||||
if f.accept(next) {
|
||||
priorFields := next.Fields
|
||||
next.Fields = udfFields
|
||||
keep, ferr := f.accept(f.ctx, next)
|
||||
next.Fields = priorFields
|
||||
if ferr != nil {
|
||||
return nil, ferr
|
||||
}
|
||||
if keep {
|
||||
return next, nil
|
||||
}
|
||||
ctx.DocumentMatchPool.Put(next)
|
||||
next, err = f.child.Next(ctx)
|
||||
}
|
||||
return nil, err
|
||||
@@ -87,12 +102,22 @@ func (f *CustomFilterSearcher) Advance(ctx *search.SearchContext, ID index.Index
|
||||
if adv == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err = loadDocValuesOnHitWithTypes(adv, f.dvReader, f.indexReader, f.fieldTypes); err != nil {
|
||||
return nil, err
|
||||
// See Next: put the loaded fields on the hit only for the callback.
|
||||
udfFields, lerr := loadDocValuesOnHitWithTypes(adv, f.dvReader, f.indexReader, f.fieldTypes)
|
||||
if lerr != nil {
|
||||
return nil, lerr
|
||||
}
|
||||
if f.accept(adv) {
|
||||
priorFields := adv.Fields
|
||||
adv.Fields = udfFields
|
||||
keep, ferr := f.accept(f.ctx, adv)
|
||||
adv.Fields = priorFields
|
||||
if ferr != nil {
|
||||
return nil, ferr
|
||||
}
|
||||
if keep {
|
||||
return adv, nil
|
||||
}
|
||||
ctx.DocumentMatchPool.Put(adv)
|
||||
return f.Next(ctx)
|
||||
}
|
||||
|
||||
|
||||
+53
-9
@@ -30,32 +30,59 @@ func init() {
|
||||
reflectStaticSizeCustomScoreSearcher = int(reflect.TypeOf(sfs).Size())
|
||||
}
|
||||
|
||||
// CustomScoreFunc defines a function which can mutate document scores.
|
||||
type CustomScoreFunc func(d *search.DocumentMatch) float64
|
||||
// CustomScoreFunc defines a function which can mutate document scores. It
|
||||
// receives the search's context so a long-running callback (e.g. a JS UDF) can
|
||||
// honor the query deadline/cancellation. A non-nil error aborts the search so
|
||||
// the failure can be surfaced to the caller rather than silently falling back
|
||||
// to the original score.
|
||||
type CustomScoreFunc func(ctx context.Context, d *search.DocumentMatch) (float64, error)
|
||||
|
||||
// CustomScoreSearcher wraps any other searcher, optionally loads doc values
|
||||
// into each DocumentMatch, then mutates the score using the supplied
|
||||
// CustomScoreFunc.
|
||||
type CustomScoreSearcher struct {
|
||||
ctx context.Context
|
||||
child search.Searcher
|
||||
mutate CustomScoreFunc
|
||||
dvReader index.DocValueReader
|
||||
indexReader index.IndexReader
|
||||
fieldTypes map[string]string
|
||||
explain bool
|
||||
}
|
||||
|
||||
func NewCustomScoreSearcher(ctx context.Context, s search.Searcher, mutate CustomScoreFunc,
|
||||
dvReader index.DocValueReader, indexReader index.IndexReader,
|
||||
fieldTypes map[string]string) *CustomScoreSearcher {
|
||||
fieldTypes map[string]string, explain bool) *CustomScoreSearcher {
|
||||
return &CustomScoreSearcher{
|
||||
ctx: ctx,
|
||||
child: s,
|
||||
mutate: mutate,
|
||||
dvReader: dvReader,
|
||||
indexReader: indexReader,
|
||||
fieldTypes: fieldTypes,
|
||||
explain: explain,
|
||||
}
|
||||
}
|
||||
|
||||
// applyScore mutates the score on the hit and, when explain is enabled,
|
||||
// replaces the explanation with a single node describing the custom score
|
||||
// result. A non-nil error from the score function is returned so the caller
|
||||
// can abort the search.
|
||||
func (f *CustomScoreSearcher) applyScore(d *search.DocumentMatch) error {
|
||||
score, err := f.mutate(f.ctx, d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.Score = score
|
||||
if f.explain {
|
||||
d.Expl = &search.Explanation{
|
||||
Value: d.Score,
|
||||
Message: "custom_score function result",
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *CustomScoreSearcher) Size() int {
|
||||
return reflectStaticSizeCustomScoreSearcher + size.SizeOfPtr +
|
||||
f.child.Size()
|
||||
@@ -67,10 +94,19 @@ func (f *CustomScoreSearcher) Next(ctx *search.SearchContext) (*search.DocumentM
|
||||
return nil, err
|
||||
}
|
||||
if next != nil {
|
||||
if err = loadDocValuesOnHitWithTypes(next, f.dvReader, f.indexReader, f.fieldTypes); err != nil {
|
||||
return nil, err
|
||||
// Put the loaded fields on the hit only for scoring, so UDF-input fields
|
||||
// don't override SearchRequest.Fields in the response.
|
||||
udfFields, lerr := loadDocValuesOnHitWithTypes(next, f.dvReader, f.indexReader, f.fieldTypes)
|
||||
if lerr != nil {
|
||||
return nil, lerr
|
||||
}
|
||||
priorFields := next.Fields
|
||||
next.Fields = udfFields
|
||||
serr := f.applyScore(next)
|
||||
next.Fields = priorFields
|
||||
if serr != nil {
|
||||
return nil, serr
|
||||
}
|
||||
next.Score = f.mutate(next)
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
@@ -81,10 +117,18 @@ func (f *CustomScoreSearcher) Advance(ctx *search.SearchContext, ID index.IndexI
|
||||
return nil, err
|
||||
}
|
||||
if adv != nil {
|
||||
if err = loadDocValuesOnHitWithTypes(adv, f.dvReader, f.indexReader, f.fieldTypes); err != nil {
|
||||
return nil, err
|
||||
// See Next: put the loaded fields on the hit only for scoring.
|
||||
udfFields, lerr := loadDocValuesOnHitWithTypes(adv, f.dvReader, f.indexReader, f.fieldTypes)
|
||||
if lerr != nil {
|
||||
return nil, lerr
|
||||
}
|
||||
priorFields := adv.Fields
|
||||
adv.Fields = udfFields
|
||||
serr := f.applyScore(adv)
|
||||
adv.Fields = priorFields
|
||||
if serr != nil {
|
||||
return nil, serr
|
||||
}
|
||||
adv.Score = f.mutate(adv)
|
||||
}
|
||||
return adv, nil
|
||||
}
|
||||
|
||||
+8
-2
@@ -68,8 +68,14 @@ func newDisjunctionSearcher(ctx context.Context, indexReader index.IndexReader,
|
||||
optionsDisjunctionOptimizable(options) {
|
||||
rv, err := optimizeCompositeSearcher(ctx, "disjunction:unadorned",
|
||||
indexReader, qsearchers, options)
|
||||
if err != nil || rv != nil {
|
||||
return rv, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rv != nil {
|
||||
for _, s := range qsearchers {
|
||||
_ = s.Close()
|
||||
}
|
||||
return rv, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+46
-38
@@ -66,11 +66,11 @@ func NewFuzzySearcher(ctx context.Context, indexReader index.IndexReader, term s
|
||||
}
|
||||
|
||||
// Note: we don't byte slice the term for a prefix because of runes.
|
||||
prefixTerm := ""
|
||||
for i, r := range term {
|
||||
if i < prefix {
|
||||
prefixTerm += string(r)
|
||||
} else {
|
||||
// we instead slice the term at the first rune boundary at/after prefix index
|
||||
prefixTerm := term
|
||||
for i := range term {
|
||||
if i >= prefix {
|
||||
prefixTerm = term[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -89,21 +89,21 @@ func NewFuzzySearcher(ctx context.Context, indexReader index.IndexReader, term s
|
||||
dictBytesRead = fuzzyCandidates.bytesRead
|
||||
}
|
||||
|
||||
var fuzzyTermMatches map[string][]string
|
||||
if ctx != nil {
|
||||
reportIOStats(ctx, dictBytesRead)
|
||||
search.RecordSearchCost(ctx, search.AddM, dictBytesRead)
|
||||
fuzzyTermMatches := ctx.Value(search.FuzzyMatchPhraseKey)
|
||||
if fuzzyTermMatches != nil {
|
||||
fuzzyTermMatches.(map[string][]string)[term] = candidates
|
||||
if ftm := ctx.Value(search.FuzzyMatchPhraseKey); ftm != nil {
|
||||
fuzzyTermMatches = ftm.(map[string][]string)
|
||||
}
|
||||
}
|
||||
if fuzzyTermMatches != nil {
|
||||
fuzzyTermMatches[term] = candidates
|
||||
}
|
||||
// check if the candidates are empty or have one term which is the term itself
|
||||
if len(candidates) == 0 || (len(candidates) == 1 && candidates[0] == term) {
|
||||
if ctx != nil {
|
||||
fuzzyTermMatches := ctx.Value(search.FuzzyMatchPhraseKey)
|
||||
if fuzzyTermMatches != nil {
|
||||
fuzzyTermMatches.(map[string][]string)[term] = []string{term}
|
||||
}
|
||||
if fuzzyTermMatches != nil {
|
||||
fuzzyTermMatches[term] = []string{term}
|
||||
}
|
||||
return NewTermSearcher(ctx, indexReader, term, field, boost, options)
|
||||
}
|
||||
@@ -156,15 +156,29 @@ func findFuzzyCandidateTerms(ctx context.Context, indexReader index.IndexReader,
|
||||
// the levenshtein automaton based iterator to collect the
|
||||
// candidate terms
|
||||
if ir, ok := indexReader.(index.IndexReaderFuzzy); ok {
|
||||
termSet := make(map[string]struct{})
|
||||
var synonymTerms map[string][]string
|
||||
if ctx != nil {
|
||||
if fts, ok := ctx.Value(search.FieldTermSynonymMapKey).(search.FieldTermSynonymMap); ok {
|
||||
synonymTerms = fts[field]
|
||||
}
|
||||
}
|
||||
// termSet is used to de-duplicate synonym terms against the candidates
|
||||
// gathered across all the segments' dictionaries.
|
||||
var termSet map[string]struct{}
|
||||
if len(synonymTerms) > 0 {
|
||||
termSet = make(map[string]struct{}, len(synonymTerms))
|
||||
}
|
||||
addCandidateTerm := func(term string, editDistance uint8) error {
|
||||
if _, exists := termSet[term]; !exists {
|
||||
termSet[term] = struct{}{}
|
||||
rv.candidates = append(rv.candidates, term)
|
||||
rv.editDistances = append(rv.editDistances, editDistance)
|
||||
if tooManyClauses(len(rv.candidates)) {
|
||||
return tooManyClausesErr(field, len(rv.candidates))
|
||||
if termSet != nil {
|
||||
if _, exists := termSet[term]; exists {
|
||||
return nil
|
||||
}
|
||||
termSet[term] = struct{}{}
|
||||
}
|
||||
rv.candidates = append(rv.candidates, term)
|
||||
rv.editDistances = append(rv.editDistances, editDistance)
|
||||
if tooManyClauses(len(rv.candidates)) {
|
||||
return tooManyClausesErr(field, len(rv.candidates))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -188,24 +202,18 @@ func findFuzzyCandidateTerms(ctx context.Context, indexReader index.IndexReader,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ctx != nil {
|
||||
if fts, ok := ctx.Value(search.FieldTermSynonymMapKey).(search.FieldTermSynonymMap); ok {
|
||||
if ts, exists := fts[field]; exists {
|
||||
for term := range ts {
|
||||
if _, exists := termSet[term]; exists {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(term, prefixTerm) {
|
||||
continue
|
||||
}
|
||||
match, editDistance := a.MatchAndDistance(term)
|
||||
if match {
|
||||
err = addCandidateTerm(term, editDistance)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
for term := range synonymTerms {
|
||||
if _, exists := termSet[term]; exists {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(term, prefixTerm) {
|
||||
continue
|
||||
}
|
||||
match, editDistance := a.MatchAndDistance(term)
|
||||
if match {
|
||||
err = addCandidateTerm(term, editDistance)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package searcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/blevesearch/bleve/v2/search"
|
||||
"github.com/blevesearch/bleve/v2/search/scorer"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
)
|
||||
|
||||
var reflectStaticSizeGeoShapeV2Searcher int
|
||||
|
||||
func init() {
|
||||
var gsv2s GeoShapeV2Searcher
|
||||
reflectStaticSizeGeoShapeV2Searcher = int(reflect.TypeOf(gsv2s).Size())
|
||||
}
|
||||
|
||||
type GeoShapeV2Searcher struct {
|
||||
geoShapeIndexReader index.GeoShapeV2FieldReader
|
||||
scorer *scorer.ConstantScorer
|
||||
|
||||
gd index.GeoShapeV2FieldDoc
|
||||
}
|
||||
|
||||
func NewGeoShapeV2Searcher(ctx context.Context, indexReader index.IndexReader,
|
||||
shape index.GeoJSON, relation string, field string, boost float64,
|
||||
options search.SearcherOptions,
|
||||
) (search.Searcher, error) {
|
||||
|
||||
if gr, ok := indexReader.(index.GeoShapeV2IndexReader); ok {
|
||||
// get the GeoShapeV2FieldReader for the specified field
|
||||
geoShapeIndexReader, err := gr.GeoShapeV2FieldReader(ctx, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// perform the search on the GeoShapeV2FieldReader with the specified
|
||||
// shape and relation
|
||||
err = geoShapeIndexReader.Search(shape, relation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &GeoShapeV2Searcher{
|
||||
geoShapeIndexReader: geoShapeIndexReader,
|
||||
scorer: scorer.NewConstantScorer(1, boost, options),
|
||||
gd: index.GeoShapeV2FieldDoc{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("indexReader does not support geoshape_v2 queries")
|
||||
}
|
||||
|
||||
// Next returns the next document match for the GeoShapeV2Searcher.
|
||||
// It retrieves the next matching document from the GeoShapeV2FieldReader
|
||||
// and scores it using the ConstantScorer.
|
||||
func (g *GeoShapeV2Searcher) Next(ctx *search.SearchContext) (*search.DocumentMatch, error) {
|
||||
match, err := g.geoShapeIndexReader.Next(g.gd.Reset())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if match == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
docMatch := g.scorer.Score(ctx, match.ID)
|
||||
return docMatch, nil
|
||||
}
|
||||
|
||||
// Advance moves the searcher to the first document with an ID greater than or equal to the specified ID.
|
||||
// It retrieves the next matching document from the GeoShapeV2FieldReader and scores it using the ConstantScorer.
|
||||
func (g *GeoShapeV2Searcher) Advance(ctx *search.SearchContext, ID index.IndexInternalID) (*search.DocumentMatch, error) {
|
||||
match, err := g.geoShapeIndexReader.Advance(ID, g.gd.Reset())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if match == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
docMatch := g.scorer.Score(ctx, match.ID)
|
||||
return docMatch, nil
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2Searcher) Close() error {
|
||||
return g.geoShapeIndexReader.Close()
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2Searcher) Count() uint64 {
|
||||
return g.geoShapeIndexReader.Count()
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2Searcher) DocumentMatchPoolSize() int {
|
||||
return 1
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2Searcher) Min() int {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2Searcher) SetQueryNorm(n float64) {
|
||||
g.scorer.SetQueryNorm(n)
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2Searcher) Size() int {
|
||||
return reflectStaticSizeGeoShapeV2Searcher + g.geoShapeIndexReader.Size() +
|
||||
g.scorer.Size() + g.gd.Size()
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2Searcher) Weight() float64 {
|
||||
return g.scorer.Weight()
|
||||
}
|
||||
+6
@@ -115,6 +115,12 @@ func bm25ScoreMetrics(ctx context.Context, field string,
|
||||
func newTermSearcherFromReader(ctx context.Context, indexReader index.IndexReader,
|
||||
reader index.TermFieldReader, term []byte, field string, boost float64,
|
||||
options search.SearcherOptions) (*TermSearcher, error) {
|
||||
// Every leaf term searcher is built here, so this is where we count against
|
||||
// the limit. Close the reader on failure since the caller won't get it back.
|
||||
if err := search.RecordTermSearcher(ctx); err != nil {
|
||||
_ = reader.Close()
|
||||
return nil, err
|
||||
}
|
||||
var count uint64
|
||||
var avgDocLength float64
|
||||
var err error
|
||||
|
||||
+18
@@ -274,6 +274,24 @@ func (so SortOrder) Compare(cachedScoring, cachedDesc []bool, i, j *DocumentMatc
|
||||
return -1
|
||||
}
|
||||
|
||||
func CompareScoreDescending(i, j *DocumentMatch) int {
|
||||
// first try to sort the two hits based on their score value
|
||||
if i.Score < j.Score {
|
||||
return 1
|
||||
}
|
||||
if i.Score > j.Score {
|
||||
return -1
|
||||
}
|
||||
// tie-break on natural index order: earlier hit sorts first
|
||||
if i.HitNumber > j.HitNumber {
|
||||
return 1
|
||||
}
|
||||
if i.HitNumber < j.HitNumber {
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (so SortOrder) RequiresScore() bool {
|
||||
for _, soi := range so {
|
||||
if soi.RequiresScoring() {
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package search
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// termSearchersCounter tracks the running total of leaf term searchers created
|
||||
// while searching a single index and the limit beyond which construction fails.
|
||||
type termSearchersCounter struct {
|
||||
limit int
|
||||
count atomic.Uint64
|
||||
}
|
||||
|
||||
// ContextWithTermSearchersCounter installs a fresh counter for the limit at
|
||||
// MaxTermSearchersKey, when that limit is positive. It is called once per index
|
||||
// search (indexImpl.SearchInContext), so the counter is scoped to that index:
|
||||
// within a single index it spans the whole query tree (all fan-out nodes share
|
||||
// one counter), but across an IndexAlias each index is counted independently.
|
||||
// context is returned unchanged and RecordTermSearcher stays a no-op.
|
||||
func ContextWithTermSearchersCounter(ctx context.Context) context.Context {
|
||||
if ctx == nil {
|
||||
return ctx
|
||||
}
|
||||
limit, ok := ctx.Value(MaxTermSearchersKey).(int)
|
||||
if !ok || limit <= 0 {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, termSearchersCounterKey,
|
||||
&termSearchersCounter{limit: limit})
|
||||
}
|
||||
|
||||
// RecordTermSearcher counts one leaf term searcher, returning an error once the
|
||||
// running total exceeds the limit. It is a no-op when no counter was installed.
|
||||
func RecordTermSearcher(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
c, ok := ctx.Value(termSearchersCounterKey).(*termSearchersCounter)
|
||||
if !ok || c == nil {
|
||||
return nil
|
||||
}
|
||||
if n := c.count.Add(1); n > uint64(c.limit) {
|
||||
return fmt.Errorf("TooManyTermSearchers [%d > bleveMaxTerms,"+
|
||||
" which is set to %d]", n, c.limit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+13
@@ -54,6 +54,9 @@ func MergeFieldTermLocations(dest []FieldTermLocation, matches []*DocumentMatch)
|
||||
n += len(dm.FieldTermLocations)
|
||||
}
|
||||
}
|
||||
if n == len(dest) {
|
||||
return dest
|
||||
}
|
||||
if cap(dest) < n {
|
||||
dest = append(make([]FieldTermLocation, 0, n), dest...)
|
||||
}
|
||||
@@ -173,6 +176,16 @@ const (
|
||||
// NestedSearchKey is used to communicate whether the search is performed
|
||||
// in an index with nested documents
|
||||
NestedSearchKey ContextKey = "_nested_search_key"
|
||||
|
||||
// MaxTermSearchersKey carries an application-set int limit on the total
|
||||
// number of leaf term searchers created for a single search; <= 0 disables
|
||||
// the check. Unlike DisjunctionMaxClauseCount, which is per fan-out node,
|
||||
// this bounds the count across the whole query tree.
|
||||
MaxTermSearchersKey ContextKey = "_max_term_searchers_key"
|
||||
|
||||
// termSearchersCounterKey carries the per-search counter installed by
|
||||
// ContextWithTermSearchersCounter.
|
||||
termSearchersCounterKey ContextKey = "_term_searchers_counter_key"
|
||||
)
|
||||
|
||||
func RecordSearchCost(ctx context.Context,
|
||||
|
||||
+1
-1
@@ -480,7 +480,7 @@ func setKnnHitsInCollector(knnHits []*search.DocumentMatch, coll *collector.TopN
|
||||
// Boost the FTS score using the KNN score
|
||||
ftsMatch.Score += knnMatch.Score
|
||||
// Combine the FTS explanation with the KNN explanation, if present
|
||||
ftsMatch.Expl.MergeWith(knnMatch.Expl)
|
||||
ftsMatch.Expl = ftsMatch.Expl.MergeWith(knnMatch.Expl)
|
||||
}
|
||||
coll.SetKNNHits(knnHits, search.HybridMergeCallbackFn(mergeFn))
|
||||
}
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
|
||||
"github.com/RoaringBitmap/roaring/v2"
|
||||
)
|
||||
|
||||
type Bitset struct {
|
||||
data []uint64
|
||||
numBits int
|
||||
exclude *roaring.Bitmap
|
||||
}
|
||||
|
||||
// NewBitset initializes a bitset capable of holding numbers up to maxVal
|
||||
func NewBitset(maxVal int, exclude *roaring.Bitmap) *Bitset {
|
||||
// We need (maxVal / 64) + 1 buckets to hold up to maxVal
|
||||
size := (maxVal / 64) + 1
|
||||
return &Bitset{
|
||||
data: make([]uint64, size),
|
||||
numBits: maxVal,
|
||||
exclude: exclude,
|
||||
}
|
||||
}
|
||||
|
||||
// Add inserts a value into the bitset (safely handles duplicates)
|
||||
func (b *Bitset) Add(val int) {
|
||||
if b.exclude != nil && b.exclude.Contains(uint32(val)) {
|
||||
return
|
||||
}
|
||||
bucket := val >> 6 // Equivalent to val / 64
|
||||
bit := uint(val & 63) // Equivalent to val % 64
|
||||
|
||||
// Set the bit to 1 using bitwise OR
|
||||
b.data[bucket] |= (1 << bit)
|
||||
}
|
||||
|
||||
// Remove deletes a value from the bitset
|
||||
func (b *Bitset) Remove(val int) {
|
||||
bucket := val >> 6
|
||||
bit := uint(val & 63)
|
||||
|
||||
// Set the bit to 0 using bitwise AND with the complement
|
||||
b.data[bucket] &^= (1 << bit)
|
||||
}
|
||||
|
||||
// Contains checks if a value exists in the bitset
|
||||
func (b *Bitset) Contains(val int) bool {
|
||||
bucket := val >> 6
|
||||
bit := uint(val & 63)
|
||||
|
||||
return (b.data[bucket] & (1 << bit)) != 0
|
||||
}
|
||||
|
||||
// Invert flips all bits in the bitset,
|
||||
// effectively turning all 1s to 0s and vice versa
|
||||
func (b *Bitset) Invert() {
|
||||
for i := range b.data {
|
||||
b.data[i] = ^b.data[i]
|
||||
}
|
||||
// the flip above sets the trailing bits beyond numBits in the last
|
||||
// bucket(s), which do not correspond to valid values - clear them so
|
||||
// that Iterate and Count never see them
|
||||
lastBucket := b.numBits >> 6
|
||||
if lastBucket < len(b.data) {
|
||||
b.data[lastBucket] &= (1 << uint(b.numBits&63)) - 1
|
||||
for i := lastBucket + 1; i < len(b.data); i++ {
|
||||
b.data[i] = 0
|
||||
}
|
||||
}
|
||||
if b.exclude != nil {
|
||||
it := b.exclude.Iterator()
|
||||
for it.HasNext() {
|
||||
bit := uint64(it.Next())
|
||||
word := bit / 64
|
||||
if word < uint64(len(b.data)) {
|
||||
b.data[word] &^= uint64(1) << (bit % 64)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate calls the provided function for every integer recorded in the bitset, in ascending order
|
||||
func (b *Bitset) Iterate(f func(int)) {
|
||||
for bucketIdx, bucket := range b.data {
|
||||
// If the entire 64-bit block is 0, skip it entirely for speed
|
||||
if bucket == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check all 64 bits in this bucket
|
||||
for bitIdx := 0; bitIdx < 64; bitIdx++ {
|
||||
if (bucket & (1 << uint(bitIdx))) != 0 {
|
||||
// Reconstruct the original integer
|
||||
originalVal := (bucketIdx << 6) + bitIdx
|
||||
f(originalVal)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bitset) Count() int {
|
||||
count := 0
|
||||
|
||||
for _, word := range b.data {
|
||||
count += bits.OnesCount64(word)
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func (b *Bitset) Clear() {
|
||||
for i := range b.data {
|
||||
b.data[i] = 0
|
||||
}
|
||||
}
|
||||
+16
@@ -89,6 +89,22 @@ type GeoShapeField interface {
|
||||
EncodedShape() []byte
|
||||
}
|
||||
|
||||
// GeoShapeV2Field represents an analyzed geo shape field
|
||||
type GeoShapeV2Field interface {
|
||||
// InnerCells returns the covering cells fully contained within the shape
|
||||
InnerCells() []uint64
|
||||
// CrossCells returns the covering cells that overlap the shape's boundary
|
||||
CrossCells() []uint64
|
||||
|
||||
// EncodedBoundingBox returns the serialized bounding box of the shape
|
||||
EncodedBoundingBox() []byte
|
||||
// EncodedShape returns the serialized shape
|
||||
EncodedShape() []byte
|
||||
|
||||
// Scores returns the shape's inner and cross cell scores
|
||||
Scores() (inner, cross uint64)
|
||||
}
|
||||
|
||||
type IPField interface {
|
||||
IP() (net.IP, error)
|
||||
}
|
||||
|
||||
+69
-8
@@ -18,18 +18,20 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
var reflectStaticSizeTermFieldDoc int
|
||||
var reflectStaticSizeTermFieldVector int
|
||||
var reflectStaticSizeGeoShapeV2FieldDoc int
|
||||
|
||||
func init() {
|
||||
var tfd TermFieldDoc
|
||||
reflectStaticSizeTermFieldDoc = int(reflect.TypeOf(tfd).Size())
|
||||
var tfv TermFieldVector
|
||||
reflectStaticSizeTermFieldVector = int(reflect.TypeOf(tfv).Size())
|
||||
var gfd GeoShapeV2FieldDoc
|
||||
reflectStaticSizeGeoShapeV2FieldDoc = int(reflect.TypeOf(gfd).Size())
|
||||
}
|
||||
|
||||
type Index interface {
|
||||
@@ -204,8 +206,9 @@ func NewIndexInternalID(buf []byte, in uint64) IndexInternalID {
|
||||
buf = make([]byte, 8)
|
||||
}
|
||||
}
|
||||
binary.BigEndian.PutUint64(buf, in)
|
||||
return buf
|
||||
id := IndexInternalID(buf)
|
||||
id.SetValue(in)
|
||||
return id
|
||||
}
|
||||
|
||||
// NewIndexInternalIDFrom creates a new IndexInternalID by copying from `other`, reusing `buf` when possible.
|
||||
@@ -225,11 +228,13 @@ func (id IndexInternalID) Compare(other IndexInternalID) int {
|
||||
}
|
||||
|
||||
// Value returns the uint64 value encoded in the IndexInternalID.
|
||||
func (id IndexInternalID) Value() (uint64, error) {
|
||||
if len(id) != 8 {
|
||||
return 0, fmt.Errorf("wrong len for IndexInternalID: %q", id)
|
||||
}
|
||||
return binary.BigEndian.Uint64(id), nil
|
||||
func (id IndexInternalID) Value() uint64 {
|
||||
return binary.BigEndian.Uint64(id)
|
||||
}
|
||||
|
||||
// SetValue overwrites the encoded uint64 value in the IndexInternalID in place.
|
||||
func (id IndexInternalID) SetValue(in uint64) {
|
||||
binary.BigEndian.PutUint64(id, in)
|
||||
}
|
||||
|
||||
type TermFieldDoc struct {
|
||||
@@ -487,6 +492,62 @@ func (a AncestorID) ToIndexInternalID(prealloc IndexInternalID) IndexInternalID
|
||||
return NewIndexInternalID(prealloc, uint64(a))
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// GeoShapeV2IndexReader is an extended index reader that supports reading and
|
||||
// querying Geo-Shape V2 data.
|
||||
type GeoShapeV2IndexReader interface {
|
||||
IndexReader
|
||||
|
||||
GeoShapeV2FieldReader(ctx context.Context, field string) (
|
||||
GeoShapeV2FieldReader, error)
|
||||
}
|
||||
|
||||
// GeoShapeV2FieldReader iterates over the documents whose shapes satisfy a
|
||||
// spatial relation with a query shape. Search must be called before Next or Advance.
|
||||
type GeoShapeV2FieldReader interface {
|
||||
// Search performs a full search and obtains all of the hits for the
|
||||
// given shape and relation.
|
||||
Search(shape GeoJSON, relation string) error
|
||||
|
||||
// Next returns the next document matching the search, or nil when it
|
||||
// reaches the end of the enumeration.
|
||||
Next(*GeoShapeV2FieldDoc) (*GeoShapeV2FieldDoc, error)
|
||||
|
||||
// Advance resets the enumeration at specified document.
|
||||
Advance(ID IndexInternalID, preAlloced *GeoShapeV2FieldDoc) (
|
||||
*GeoShapeV2FieldDoc, error)
|
||||
|
||||
// Count returns the number of documents matched by the preceding Search.
|
||||
Count() uint64
|
||||
|
||||
// Close releases any resources associated with the reader.
|
||||
Close() error
|
||||
|
||||
// Size returns the size of the reader in bytes.
|
||||
Size() int
|
||||
}
|
||||
|
||||
// GeoShapeV2FieldDoc represents a single hit from a geo shape v2 search.
|
||||
type GeoShapeV2FieldDoc struct {
|
||||
ID IndexInternalID
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2FieldDoc) Size() int {
|
||||
return reflectStaticSizeGeoShapeV2FieldDoc + sizeOfPtr + len(g.ID)
|
||||
}
|
||||
|
||||
func (g *GeoShapeV2FieldDoc) Reset() *GeoShapeV2FieldDoc {
|
||||
// remember the []byte used for the ID
|
||||
id := g.ID
|
||||
// idiom to copy over from empty GeoShapeV2FieldDoc (0 allocations)
|
||||
*g = GeoShapeV2FieldDoc{}
|
||||
// reuse the []byte already allocated (and reset len to 0)
|
||||
g.ID = id[:0]
|
||||
return g
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
// Default no-op implementation. Is called before writing any user data to a file.
|
||||
var WriterHook func(context []byte) (string, func(data []byte) []byte, error)
|
||||
|
||||
|
||||
+13
@@ -44,4 +44,17 @@ type GeoJSON interface {
|
||||
|
||||
// Value returns the byte value for the shape.
|
||||
Value() ([]byte, error)
|
||||
|
||||
// ---------------------- geo shape v2 methods ------------------------
|
||||
|
||||
// IndexCells returns the covering cells computed with the
|
||||
// index-time coverer.
|
||||
IndexCells() (inner, cross []uint64)
|
||||
|
||||
// QueryCells returns the covering cells computed with the
|
||||
// query-time coverer.
|
||||
QueryCells() (inner, cross []uint64)
|
||||
|
||||
// BoundingBox returns the bounding box of the shape
|
||||
BoundingBox() GeoJSON
|
||||
}
|
||||
+4
@@ -95,6 +95,10 @@ func OptimizationRequiresBinaryIndex(optimization string) bool {
|
||||
const TrainedIndexFileName = "trained_index"
|
||||
const TrainingKey = "_training"
|
||||
|
||||
type TrainingParams struct {
|
||||
NumCentroids int
|
||||
}
|
||||
|
||||
const TrainedIndexCallback = "_trained_index_callback"
|
||||
|
||||
type TrainedIndexCallbackFn func(string) (interface{}, error)
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geojson
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/s2"
|
||||
)
|
||||
|
||||
// Circle represents a custom circle type and it
|
||||
// implements the index.GeoJSON interface.
|
||||
type Circle struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices []float64 `json:"coordinates"`
|
||||
Radius string `json:"radius"`
|
||||
radiusInMeters float64
|
||||
s2cap *s2.Cap
|
||||
}
|
||||
|
||||
func NewGeoCircle(points []float64,
|
||||
radius string) index.GeoJSON {
|
||||
r, err := ParseDistance(radius)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
rv := &Circle{
|
||||
Typ: CircleType,
|
||||
Vertices: points,
|
||||
Radius: radius,
|
||||
radiusInMeters: r,
|
||||
}
|
||||
rv.init()
|
||||
|
||||
return rv
|
||||
}
|
||||
|
||||
func (c *Circle) Type() string {
|
||||
return strings.ToLower(c.Typ)
|
||||
}
|
||||
|
||||
func (c *Circle) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(c)
|
||||
}
|
||||
|
||||
func (c *Circle) init() {
|
||||
if c.s2cap == nil {
|
||||
c.s2cap = s2Cap(c.Vertices, c.radiusInMeters)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Circle) Marshal() ([]byte, error) {
|
||||
c.init()
|
||||
|
||||
var b bytes.Buffer
|
||||
b.Grow(40)
|
||||
w := bufio.NewWriter(&b)
|
||||
err := c.s2cap.Encode(w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return append([]byte{CircleTypePrefix}, b.Bytes()...), nil
|
||||
}
|
||||
|
||||
func (c *Circle) Intersects(other index.GeoJSON) (bool, error) {
|
||||
c.init()
|
||||
|
||||
return checkCircleIntersectsShape(c.s2cap, c, other)
|
||||
}
|
||||
|
||||
func (c *Circle) Contains(other index.GeoJSON) (bool, error) {
|
||||
c.init()
|
||||
return checkCircleContainsShape(c.s2cap, c, other)
|
||||
}
|
||||
|
||||
func (c *Circle) UnmarshalJSON(data []byte) error {
|
||||
tmp := struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices []float64 `json:"coordinates"`
|
||||
Radius string `json:"radius"`
|
||||
}{}
|
||||
|
||||
err := jsoniter.Unmarshal(data, &tmp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Typ = tmp.Typ
|
||||
c.Vertices = tmp.Vertices
|
||||
c.Radius = tmp.Radius
|
||||
if tmp.Radius != "" {
|
||||
c.radiusInMeters, err = ParseDistance(tmp.Radius)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// IndexCells returns the circle's covering partitioned into inner cells
|
||||
// (fully contained in the cap built from the center and radiusInMeters)
|
||||
// and cross cells (overlapping the cap's boundary).
|
||||
func (c *Circle) IndexCells() (inner, cross []uint64) {
|
||||
c.init()
|
||||
if c.s2cap == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return indexCellsFromRegion(*c.s2cap)
|
||||
}
|
||||
|
||||
// QueryCells returns the circle's query-time covering, partitioned the same
|
||||
// way as IndexCells.
|
||||
func (c *Circle) QueryCells() (inner, cross []uint64) {
|
||||
c.init()
|
||||
if c.s2cap == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return queryCellsFromRegion(*c.s2cap)
|
||||
}
|
||||
|
||||
func (c *Circle) BoundingBox() index.GeoJSON {
|
||||
c.init()
|
||||
if c.s2cap == nil {
|
||||
return envelopeFromRect(s2.EmptyRect())
|
||||
}
|
||||
return envelopeFromRect(c.s2cap.RectBound())
|
||||
}
|
||||
|
||||
func (c *Circle) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
c.init()
|
||||
return StripCoveringTerms(s.GetIndexTermsForRegion(c.s2cap.CapBound(), ""))
|
||||
}
|
||||
|
||||
func (c *Circle) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
c.init()
|
||||
return StripCoveringTerms(s.GetQueryTermsForRegion(c.s2cap.CapBound(), ""))
|
||||
}
|
||||
|
||||
// checkCircleIntersectsShape checks for intersection of the
|
||||
// shape in the document with the circle.
|
||||
func checkCircleIntersectsShape(s2cap *s2.Cap, shapeIn,
|
||||
other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
if s2cap.ContainsPoint(*p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check the intersection for any point in the collection.
|
||||
for _, point := range p2.s2points {
|
||||
if s2cap.ContainsPoint(*point) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a polygon.
|
||||
if p2, ok := other.(*Polygon); ok {
|
||||
centerPoint := s2cap.Center()
|
||||
projected := p2.s2pgn.Project(¢erPoint)
|
||||
distance := projected.Distance(centerPoint)
|
||||
return distance <= s2cap.Radius(), nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipolygon.
|
||||
if p2, ok := other.(*MultiPolygon); ok {
|
||||
// check the intersection for any polygon in the collection.
|
||||
for _, s2pgn := range p2.s2pgns {
|
||||
centerPoint := s2cap.Center()
|
||||
projected := s2pgn.Project(¢erPoint)
|
||||
distance := projected.Distance(centerPoint)
|
||||
if distance <= s2cap.Radius() {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a linestring.
|
||||
if p2, ok := other.(*LineString); ok {
|
||||
projected, _ := p2.pl.Project(s2cap.Center())
|
||||
distance := projected.Distance(s2cap.Center())
|
||||
return distance <= s2cap.Radius(), nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multilinestring.
|
||||
if p2, ok := other.(*MultiLineString); ok {
|
||||
for _, pl := range p2.pls {
|
||||
projected, _ := pl.Project(s2cap.Center())
|
||||
distance := projected.Distance(s2cap.Center())
|
||||
if distance <= s2cap.Radius() {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if gc, ok := other.(*GeometryCollection); ok {
|
||||
// check whether the circle intersects with any of the
|
||||
// member shapes within the geometrycollection.
|
||||
if geometryCollectionIntersectsShape(gc, shapeIn) {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a circle.
|
||||
if c, ok := other.(*Circle); ok {
|
||||
if s2cap.Intersects(*c.s2cap) {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a envelope.
|
||||
if e, ok := other.(*Envelope); ok {
|
||||
if e.r.ContainsPoint(s2cap.Center()) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
latlngs := []s2.LatLng{e.r.Vertex(0), e.r.Vertex(1),
|
||||
e.r.Vertex(2), e.r.Vertex(3), e.r.Vertex(0)}
|
||||
pl := s2.PolylineFromLatLngs(latlngs)
|
||||
projected, _ := pl.Project(s2cap.Center())
|
||||
distance := projected.Distance(s2cap.Center())
|
||||
if distance <= s2cap.Radius() {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unknown geojson type: %s"+
|
||||
" found in document", other.Type())
|
||||
}
|
||||
|
||||
// checkCircleContainsShape checks for containment of the
|
||||
// shape in the document with the circle.
|
||||
func checkCircleContainsShape(s2cap *s2.Cap,
|
||||
shapeIn, other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
if s2cap.ContainsPoint(*p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check the intersection for every point in the collection.
|
||||
for _, point := range p2.s2points {
|
||||
if !s2cap.ContainsPoint(*point) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a polygon.
|
||||
if p2, ok := other.(*Polygon); ok {
|
||||
for i := 0; i < p2.s2pgn.NumEdges(); i++ {
|
||||
edge := p2.s2pgn.Edge(i)
|
||||
if !s2cap.ContainsPoint(edge.V0) ||
|
||||
!s2cap.ContainsPoint(edge.V1) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipolygon.
|
||||
if p2, ok := other.(*MultiPolygon); ok {
|
||||
// check the containment for every polygon in the collection.
|
||||
for _, s2pgn := range p2.s2pgns {
|
||||
for i := 0; i < s2pgn.NumEdges(); i++ {
|
||||
edge := s2pgn.Edge(i)
|
||||
if !s2cap.ContainsPoint(edge.V0) ||
|
||||
!s2cap.ContainsPoint(edge.V1) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a linestring.
|
||||
if p2, ok := other.(*LineString); ok {
|
||||
for i := 0; i < p2.pl.NumEdges(); i++ {
|
||||
edge := p2.pl.Edge(i)
|
||||
// check whether both the end vertices are inside the circle.
|
||||
if s2cap.ContainsPoint(edge.V0) &&
|
||||
s2cap.ContainsPoint(edge.V1) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multilinestring.
|
||||
if p2, ok := other.(*MultiLineString); ok {
|
||||
for _, pl := range p2.pls {
|
||||
for i := 0; i < pl.NumEdges(); i++ {
|
||||
edge := pl.Edge(i)
|
||||
// check whether both the end vertices are inside the circle.
|
||||
if !(s2cap.ContainsPoint(edge.V0) && s2cap.ContainsPoint(edge.V1)) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
if gc, ok := other.(*GeometryCollection); ok {
|
||||
for _, shape := range gc.Members() {
|
||||
contains, err := shapeIn.Contains(shape)
|
||||
if err == nil && !contains {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a circle.
|
||||
if c, ok := other.(*Circle); ok {
|
||||
if s2cap.Contains(*c.s2cap) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a envelope.
|
||||
if e, ok := other.(*Envelope); ok {
|
||||
for i := 0; i < 4; i++ {
|
||||
if !s2cap.ContainsPoint(
|
||||
s2.PointFromLatLng(e.r.Vertex(i))) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unknown geojson type: %s"+
|
||||
" found in document", other.Type())
|
||||
}
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geojson
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/s2"
|
||||
)
|
||||
|
||||
// Envelope represents the envelope/bounding box type and it
|
||||
// implements the index.GeoJSON interface.
|
||||
type Envelope struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices [][]float64 `json:"coordinates"`
|
||||
r *s2.Rect
|
||||
}
|
||||
|
||||
func NewGeoEnvelope(points [][]float64) index.GeoJSON {
|
||||
rv := &Envelope{Vertices: points, Typ: EnvelopeType}
|
||||
rv.init()
|
||||
|
||||
return rv
|
||||
}
|
||||
|
||||
func (e *Envelope) Type() string {
|
||||
return strings.ToLower(e.Typ)
|
||||
}
|
||||
|
||||
func (e *Envelope) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(e)
|
||||
}
|
||||
|
||||
func (e *Envelope) init() {
|
||||
if e.r == nil {
|
||||
e.r = s2RectFromBounds(e.Vertices[0], e.Vertices[1])
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Envelope) Marshal() ([]byte, error) {
|
||||
e.init()
|
||||
|
||||
var b bytes.Buffer
|
||||
b.Grow(50)
|
||||
w := bufio.NewWriter(&b)
|
||||
err := e.r.Encode(w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return append([]byte{EnvelopeTypePrefix}, b.Bytes()...), nil
|
||||
}
|
||||
|
||||
func (e *Envelope) Intersects(other index.GeoJSON) (bool, error) {
|
||||
e.init()
|
||||
|
||||
return checkEnvelopeIntersectsShape(e.r, e, other)
|
||||
}
|
||||
|
||||
func (e *Envelope) Contains(other index.GeoJSON) (bool, error) {
|
||||
e.init()
|
||||
|
||||
return checkEnvelopeContainsShape(e.r, e, other)
|
||||
}
|
||||
|
||||
// IndexCells returns the envelope's covering partitioned into inner cells
|
||||
// (fully contained in the rectangle) and cross cells (overlapping its
|
||||
// boundary).
|
||||
func (e *Envelope) IndexCells() (inner, cross []uint64) {
|
||||
e.init()
|
||||
if e.r == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return indexCellsFromRegion(*e.r)
|
||||
}
|
||||
|
||||
// QueryCells returns the envelope's query-time covering, partitioned the
|
||||
// same way as IndexCells.
|
||||
func (e *Envelope) QueryCells() (inner, cross []uint64) {
|
||||
e.init()
|
||||
if e.r == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return queryCellsFromRegion(*e.r)
|
||||
}
|
||||
|
||||
func (e *Envelope) BoundingBox() index.GeoJSON {
|
||||
e.init()
|
||||
if e.r == nil {
|
||||
return envelopeFromRect(s2.EmptyRect())
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *Envelope) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
e.init()
|
||||
return StripCoveringTerms(s.GetIndexTermsForRegion(e.r.CapBound(), ""))
|
||||
}
|
||||
|
||||
func (e *Envelope) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
e.init()
|
||||
return StripCoveringTerms(s.GetQueryTermsForRegion(e.r.CapBound(), ""))
|
||||
}
|
||||
|
||||
// checkEnvelopeIntersectsShape checks whether the given shape in
|
||||
// the document is intersecting with the envelope/rectangle.
|
||||
func checkEnvelopeIntersectsShape(s2rect *s2.Rect, shapeIn,
|
||||
other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
if s2rect.ContainsPoint(*p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check the intersection for any point in the collection.
|
||||
for _, point := range p2.s2points {
|
||||
if s2rect.ContainsPoint(*point) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a polygon.
|
||||
if pgn, ok := other.(*Polygon); ok {
|
||||
if rectangleIntersectsWithPolygons(s2rect,
|
||||
[]*s2.Polygon{pgn.s2pgn}) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipolygon.
|
||||
if mpgn, ok := other.(*MultiPolygon); ok {
|
||||
// check the intersection for any polygon in the collection.
|
||||
if rectangleIntersectsWithPolygons(s2rect, mpgn.s2pgns) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a linestring.
|
||||
if ls, ok := other.(*LineString); ok {
|
||||
if rectangleIntersectsWithLineStrings(s2rect,
|
||||
[]*s2.Polyline{ls.pl}) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multilinestring.
|
||||
if mls, ok := other.(*MultiLineString); ok {
|
||||
if rectangleIntersectsWithLineStrings(s2rect, mls.pls) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if gc, ok := other.(*GeometryCollection); ok {
|
||||
// check for the intersection of every member shape
|
||||
// within the geometrycollection.
|
||||
if geometryCollectionIntersectsShape(gc, shapeIn) {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a circle.
|
||||
if c, ok := other.(*Circle); ok {
|
||||
// check if the distance of the center of the circle from the
|
||||
// rectangle is less than the radius of the circle.
|
||||
if s2rect.DistanceToLatLng(s2.LatLngFromPoint(c.s2cap.Center())) <=
|
||||
c.s2cap.Radius() {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a envelope.
|
||||
if e, ok := other.(*Envelope); ok {
|
||||
if s2rect.Intersects(*e.r) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unknown geojson type: %s"+
|
||||
" found in document", other.Type())
|
||||
}
|
||||
|
||||
// checkEnvelopeContainsShape checks whether the given shape in
|
||||
// the document is contained within the envelope/rectangle.
|
||||
func checkEnvelopeContainsShape(s2rect *s2.Rect, shapeIn,
|
||||
other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
if s2rect.ContainsPoint(*p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check the intersection for any point in the collection.
|
||||
for _, point := range p2.s2points {
|
||||
if !s2rect.ContainsPoint(*point) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a polygon.
|
||||
if p2, ok := other.(*Polygon); ok {
|
||||
return s2rect.Contains(p2.s2pgn.RectBound()), nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipolygon.
|
||||
if p2, ok := other.(*MultiPolygon); ok {
|
||||
// check the containment for every polygon in the collection.
|
||||
for _, s2pgn := range p2.s2pgns {
|
||||
if !s2rect.Contains(s2pgn.RectBound()) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a linestring.
|
||||
if p2, ok := other.(*LineString); ok {
|
||||
return s2rect.Contains(p2.pl.RectBound()), nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multilinestring.
|
||||
if p2, ok := other.(*MultiLineString); ok {
|
||||
for _, pl := range p2.pls {
|
||||
if !s2rect.Contains(pl.RectBound()) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
if gc, ok := other.(*GeometryCollection); ok {
|
||||
for _, shape := range gc.Members() {
|
||||
contains, err := shapeIn.Contains(shape)
|
||||
if err == nil && !contains {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a circle.
|
||||
if c, ok := other.(*Circle); ok {
|
||||
if s2rect.Contains(c.s2cap.RectBound()) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a envelope.
|
||||
if e, ok := other.(*Envelope); ok {
|
||||
if s2rect.Contains(*e.r) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unknown geojson type: %s"+
|
||||
" found in document", other.Type())
|
||||
}
|
||||
-12
@@ -18,7 +18,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/s1"
|
||||
"github.com/blevesearch/geo/s2"
|
||||
)
|
||||
@@ -123,17 +122,6 @@ func polygonsIntersectsPoint(s2pgns []*s2.Polygon,
|
||||
return s2.NewContainsPointQuery(idx, s2.VertexModelClosed).Contains(*point)
|
||||
}
|
||||
|
||||
func geometryCollectionIntersectsShape(gc *GeometryCollection,
|
||||
shapeIn index.GeoJSON) bool {
|
||||
for _, shape := range gc.Members() {
|
||||
intersects, err := shapeIn.Intersects(shape)
|
||||
if err == nil && intersects {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func polygonsContainsLineStrings(s2pgns []*s2.Polygon,
|
||||
pls []*s2.Polyline) bool {
|
||||
checker := s2.NewCrossingEdgeQuery(s2.NewShapeIndex())
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// Copyright (c) 2022 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geojson
|
||||
|
||||
import (
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
)
|
||||
|
||||
// s2Serializable is an optional interface for implementations
|
||||
// supporting custom serialisation of data based out of s2's
|
||||
// encode method.
|
||||
type s2Serializable interface {
|
||||
// Marshal implementation should encode the shape using the
|
||||
// s2's encode methods with appropriate prefix bytes to
|
||||
// identify the type of the contents.
|
||||
Marshal() ([]byte, error)
|
||||
}
|
||||
|
||||
const (
|
||||
PointType = "point"
|
||||
MultiPointType = "multipoint"
|
||||
LineStringType = "linestring"
|
||||
MultiLineStringType = "multilinestring"
|
||||
PolygonType = "polygon"
|
||||
MultiPolygonType = "multipolygon"
|
||||
GeometryCollectionType = "geometrycollection"
|
||||
CircleType = "circle"
|
||||
EnvelopeType = "envelope"
|
||||
)
|
||||
|
||||
// These are the byte prefixes for identifying the
|
||||
// shape contained within the doc values byte slice
|
||||
// while decoding the contents during the query
|
||||
// filtering phase.
|
||||
const (
|
||||
PointTypePrefix = byte(1)
|
||||
MultiPointTypePrefix = byte(2)
|
||||
LineStringTypePrefix = byte(3)
|
||||
MultiLineStringTypePrefix = byte(4)
|
||||
PolygonTypePrefix = byte(5)
|
||||
MultiPolygonTypePrefix = byte(6)
|
||||
GeometryCollectionTypePrefix = byte(7)
|
||||
CircleTypePrefix = byte(8)
|
||||
EnvelopeTypePrefix = byte(9)
|
||||
)
|
||||
|
||||
// compositeShape is an optional interface for the
|
||||
// composite geoJSON shapes which is composed of
|
||||
// multiple spatial shapes within it. Composite shapes
|
||||
// like multipoint, multilinestring, multipolygon and
|
||||
// geometrycollection shapes are supposed to implement
|
||||
// this interface.
|
||||
type compositeShape interface {
|
||||
// Members implementation returns the
|
||||
// geoJSON shapes composed within the shape.
|
||||
Members() []index.GeoJSON
|
||||
}
|
||||
-1830
File diff suppressed because it is too large.
Load diff
+6
-150
@@ -48,7 +48,7 @@ type GeoShape struct {
|
||||
func FilterGeoShapesOnRelation(shape index.GeoJSON, targetShapeBytes []byte,
|
||||
relation string, reader **bytes.Reader, bufPool *s2.GeoBufferPool) (bool, error) {
|
||||
|
||||
shapeInDoc, err := extractShapesFromBytes(targetShapeBytes, reader, bufPool)
|
||||
shapeInDoc, err := ExtractShapesFromBytes(targetShapeBytes, reader, bufPool)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -56,9 +56,9 @@ func FilterGeoShapesOnRelation(shape index.GeoJSON, targetShapeBytes []byte,
|
||||
return filterShapes(shape, shapeInDoc, relation)
|
||||
}
|
||||
|
||||
// extractShapesFromBytes unmarshal the bytes to retrieve the
|
||||
// ExtractShapesFromBytes unmarshal the bytes to retrieve the
|
||||
// embedded geojson shape.
|
||||
func extractShapesFromBytes(targetShapeBytes []byte, r **bytes.Reader, bufPool *s2.GeoBufferPool) (
|
||||
func ExtractShapesFromBytes(targetShapeBytes []byte, r **bytes.Reader, bufPool *s2.GeoBufferPool) (
|
||||
index.GeoJSON, error) {
|
||||
if (*r) == nil {
|
||||
*r = bytes.NewReader(targetShapeBytes[1:])
|
||||
@@ -171,7 +171,7 @@ func extractShapesFromBytes(targetShapeBytes []byte, r **bytes.Reader, bufPool *
|
||||
gc := &GeometryCollection{Shapes: make([]index.GeoJSON, numShapes)}
|
||||
|
||||
for i := int32(0); i < numShapes; i++ {
|
||||
shape, err := extractShapesFromBytes(inputBytes[:lengths[i]], r, nil)
|
||||
shape, err := ExtractShapesFromBytes(inputBytes[:lengths[i]], r, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -327,8 +327,6 @@ func ParseGeoJSONShape(input []byte) (index.GeoJSON, error) {
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown shape type: %s", sType)
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// NewGeoJsonShape instantiate a geojson shape/circle or
|
||||
@@ -408,7 +406,7 @@ var GlueBytes = []byte("##")
|
||||
|
||||
// NewGeometryCollection instantiate a geometrycollection
|
||||
// and prefix the byte contents with certain glue bytes that
|
||||
// can be used later while filering the doc values.
|
||||
// can be used later while filtering the doc values.
|
||||
func NewGeometryCollection(shapes []*GeoShape) (
|
||||
index.GeoJSON, []byte, error) {
|
||||
for _, shape := range shapes {
|
||||
@@ -454,7 +452,7 @@ func NewGeometryCollection(shapes []*GeoShape) (
|
||||
|
||||
// NewGeoCircleShape instantiate a circle shape and
|
||||
// prefix the byte contents with certain glue bytes that
|
||||
// can be used later while filering the doc values.
|
||||
// can be used later while filtering the doc values.
|
||||
func NewGeoCircleShape(cp []float64,
|
||||
radius string) (*Circle, []byte, error) {
|
||||
r, err := ParseDistance(radius)
|
||||
@@ -472,145 +470,3 @@ func NewGeoCircleShape(cp []float64,
|
||||
|
||||
return rv, vbytes, nil
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
func (p *Point) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
p.init()
|
||||
terms := s.GetIndexTermsForPoint(*p.s2point, "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
func (p *Point) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
p.init()
|
||||
terms := s.GetQueryTermsForPoint(*p.s2point, "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
func (mp *MultiPoint) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
mp.init()
|
||||
var rv []string
|
||||
for _, s2point := range mp.s2points {
|
||||
terms := s.GetIndexTermsForPoint(*s2point, "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
mp.init()
|
||||
var rv []string
|
||||
for _, s2point := range mp.s2points {
|
||||
terms := s.GetQueryTermsForPoint(*s2point, "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
func (ls *LineString) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
ls.init()
|
||||
terms := s.GetIndexTermsForRegion(ls.pl.CapBound(), "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
func (ls *LineString) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
ls.init()
|
||||
terms := s.GetQueryTermsForRegion(ls.pl.CapBound(), "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
func (mls *MultiLineString) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
mls.init()
|
||||
var rv []string
|
||||
for _, ls := range mls.pls {
|
||||
terms := s.GetIndexTermsForRegion(ls.CapBound(), "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
mls.init()
|
||||
|
||||
var rv []string
|
||||
for _, ls := range mls.pls {
|
||||
terms := s.GetQueryTermsForRegion(ls.CapBound(), "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
func (mp *MultiPolygon) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
mp.init()
|
||||
|
||||
var rv []string
|
||||
for _, s2pgn := range mp.s2pgns {
|
||||
terms := s.GetIndexTermsForRegion(s2pgn.CapBound(), "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
mp.init()
|
||||
|
||||
var rv []string
|
||||
for _, s2pgn := range mp.s2pgns {
|
||||
terms := s.GetQueryTermsForRegion(s2pgn.CapBound(), "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
func (pgn *Polygon) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
pgn.init()
|
||||
terms := s.GetIndexTermsForRegion(
|
||||
pgn.s2pgn.CapBound(), "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
func (pgn *Polygon) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
pgn.init()
|
||||
terms := s.GetQueryTermsForRegion(
|
||||
pgn.s2pgn.CapBound(), "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
func (c *Circle) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
c.init()
|
||||
return StripCoveringTerms(s.GetIndexTermsForRegion(c.s2cap.CapBound(), ""))
|
||||
}
|
||||
|
||||
func (c *Circle) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
c.init()
|
||||
return StripCoveringTerms(s.GetQueryTermsForRegion(c.s2cap.CapBound(), ""))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
func (e *Envelope) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
e.init()
|
||||
return StripCoveringTerms(s.GetIndexTermsForRegion(e.r.CapBound(), ""))
|
||||
}
|
||||
|
||||
func (e *Envelope) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
e.init()
|
||||
return StripCoveringTerms(s.GetQueryTermsForRegion(e.r.CapBound(), ""))
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geojson
|
||||
|
||||
import "github.com/blevesearch/geo/s2"
|
||||
|
||||
// Region coverer configuration for the geo shape v2 index.
|
||||
const (
|
||||
minCellLevel = 0
|
||||
maxCellLevel = 16
|
||||
cellLevelMod = 1
|
||||
maxIndexCells = 200
|
||||
maxQueryCells = 1000
|
||||
)
|
||||
|
||||
var regionCovererIndexV2 = &s2.RegionCoverer{
|
||||
MinLevel: minCellLevel,
|
||||
MaxLevel: maxCellLevel,
|
||||
LevelMod: cellLevelMod,
|
||||
MaxCells: maxIndexCells,
|
||||
}
|
||||
|
||||
var regionCovererQueryV2 = &s2.RegionCoverer{
|
||||
MinLevel: minCellLevel,
|
||||
MaxLevel: maxCellLevel,
|
||||
LevelMod: cellLevelMod,
|
||||
MaxCells: maxQueryCells,
|
||||
}
|
||||
|
||||
// pointCell returns the single maxCellLevel cell that contains a point.
|
||||
func pointCell(p s2.Point) uint64 {
|
||||
return uint64(s2.CellIDFromLatLng(s2.LatLngFromPoint(p)).Parent(maxCellLevel))
|
||||
}
|
||||
|
||||
// envelopeFromRect builds an Envelope GeoJSON from an s2.Rect.
|
||||
func envelopeFromRect(r s2.Rect) *Envelope {
|
||||
lo := r.Lo() // (minLat, minLng)
|
||||
hi := r.Hi() // (maxLat, maxLng)
|
||||
rc := r
|
||||
return &Envelope{
|
||||
Typ: EnvelopeType,
|
||||
Vertices: [][]float64{
|
||||
{lo.Lng.Degrees(), hi.Lat.Degrees()},
|
||||
{hi.Lng.Degrees(), lo.Lat.Degrees()},
|
||||
},
|
||||
r: &rc,
|
||||
}
|
||||
}
|
||||
|
||||
// cellsFromRegion covers any s2.Region with the given coverer and partitions
|
||||
// the single covering into inner cells (region fully contains the cell) and
|
||||
// cross cells (boundary cells).
|
||||
//
|
||||
// Because the partition comes from one covering, the two sets are disjoint and
|
||||
// exhaustive over the region. For regions without area (Point, Polyline,
|
||||
// RegionUnion of those) ContainsCell is always false, so every cell is a cross
|
||||
// cell and inner is nil.
|
||||
func cellsFromRegion(region s2.Region, coverer *s2.RegionCoverer) (inner, cross []uint64) {
|
||||
covering := coverer.Covering(region)
|
||||
inner = make([]uint64, 0, len(covering))
|
||||
cross = make([]uint64, 0, len(covering))
|
||||
for _, id := range covering {
|
||||
if region.ContainsCell(s2.CellFromCellID(id)) {
|
||||
inner = append(inner, uint64(id))
|
||||
} else {
|
||||
cross = append(cross, uint64(id))
|
||||
}
|
||||
}
|
||||
return inner, cross
|
||||
}
|
||||
|
||||
// indexCellsFromRegion partitions the index-time covering of the region.
|
||||
func indexCellsFromRegion(region s2.Region) (inner, cross []uint64) {
|
||||
return cellsFromRegion(region, regionCovererIndexV2)
|
||||
}
|
||||
|
||||
// queryCellsFromRegion partitions the query-time covering of the region.
|
||||
func queryCellsFromRegion(region s2.Region) (inner, cross []uint64) {
|
||||
return cellsFromRegion(region, regionCovererQueryV2)
|
||||
}
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geojson
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/s2"
|
||||
)
|
||||
|
||||
// GeometryCollection represents the geoJSON geometryCollection type
|
||||
// and it implements the index.GeoJSON interface as well as the
|
||||
// compositeShape interface.
|
||||
type GeometryCollection struct {
|
||||
Typ string `json:"type"`
|
||||
Shapes []index.GeoJSON `json:"geometries"`
|
||||
}
|
||||
|
||||
func (gc *GeometryCollection) Type() string {
|
||||
return strings.ToLower(gc.Typ)
|
||||
}
|
||||
|
||||
func (gc *GeometryCollection) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(gc)
|
||||
}
|
||||
|
||||
func (gc *GeometryCollection) Members() []index.GeoJSON {
|
||||
shapes := make([]index.GeoJSON, 0, len(gc.Shapes))
|
||||
for _, shape := range gc.Shapes {
|
||||
if cs, ok := shape.(compositeShape); ok {
|
||||
shapes = append(shapes, cs.Members()...)
|
||||
} else {
|
||||
shapes = append(shapes, shape)
|
||||
}
|
||||
}
|
||||
return shapes
|
||||
}
|
||||
|
||||
func (gc *GeometryCollection) Marshal() ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
b.Grow(512)
|
||||
w := bufio.NewWriter(&b)
|
||||
|
||||
// first write the number of shapes.
|
||||
count := int32(len(gc.Shapes))
|
||||
err := binary.Write(w, binary.BigEndian, count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var res []byte
|
||||
for _, shape := range gc.Shapes {
|
||||
if s, ok := shape.(s2Serializable); ok {
|
||||
sb, err := s.Marshal()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// write the length of each shape.
|
||||
err = binary.Write(w, binary.BigEndian, int32(len(sb)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// track the shape contents.
|
||||
res = append(res, sb...)
|
||||
}
|
||||
}
|
||||
w.Flush()
|
||||
|
||||
return append([]byte{GeometryCollectionTypePrefix}, append(b.Bytes(), res...)...), nil
|
||||
}
|
||||
|
||||
func (gc *GeometryCollection) Intersects(other index.GeoJSON) (bool, error) {
|
||||
for _, shape := range gc.Members() {
|
||||
|
||||
intersects, err := shape.Intersects(other)
|
||||
if intersects && err == nil {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (gc *GeometryCollection) Contains(other index.GeoJSON) (bool, error) {
|
||||
// handle composite target shapes explicitly
|
||||
if cs, ok := other.(compositeShape); ok {
|
||||
otherShapes := cs.Members()
|
||||
shapesFoundWithIn := make(map[int]struct{})
|
||||
|
||||
nextShape:
|
||||
for pos, shapeInDoc := range otherShapes {
|
||||
for _, shape := range gc.Members() {
|
||||
within, err := shape.Contains(shapeInDoc)
|
||||
if within && err == nil {
|
||||
shapesFoundWithIn[pos] = struct{}{}
|
||||
continue nextShape
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return len(shapesFoundWithIn) == len(otherShapes), nil
|
||||
}
|
||||
|
||||
for _, shape := range gc.Members() {
|
||||
within, err := shape.Contains(other)
|
||||
if within && err == nil {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// aggregateCells merges the member shapes' inner/cross cell coverings into a
|
||||
// single deduplicated pair. A cell reported as inner by any member is fully
|
||||
// contained in the union of the members, so it stays inner even when another
|
||||
// member reports the same cell as a cross cell. The results are in no
|
||||
// particular order.
|
||||
func (gc *GeometryCollection) aggregateCells(
|
||||
cells func(index.GeoJSON) (inner, cross []uint64)) (inner, cross []uint64) {
|
||||
innerSet := make(map[uint64]struct{})
|
||||
crossSet := make(map[uint64]struct{})
|
||||
for _, s := range gc.Shapes {
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
in, cr := cells(s)
|
||||
for _, cell := range in {
|
||||
innerSet[cell] = struct{}{}
|
||||
}
|
||||
for _, cell := range cr {
|
||||
crossSet[cell] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
inner = make([]uint64, 0, len(innerSet))
|
||||
for cell := range innerSet {
|
||||
inner = append(inner, cell)
|
||||
}
|
||||
cross = make([]uint64, 0, len(crossSet))
|
||||
for cell := range crossSet {
|
||||
// inner wins: the cell is fully contained in some member,
|
||||
// hence in the collection as a whole
|
||||
if _, ok := innerSet[cell]; ok {
|
||||
continue
|
||||
}
|
||||
cross = append(cross, cell)
|
||||
}
|
||||
return inner, cross
|
||||
}
|
||||
|
||||
// IndexCells returns the union of the member shapes' coverings, deduplicated
|
||||
// and reconciled (see aggregateCells).
|
||||
func (gc *GeometryCollection) IndexCells() (inner, cross []uint64) {
|
||||
return gc.aggregateCells(func(s index.GeoJSON) ([]uint64, []uint64) {
|
||||
return s.IndexCells()
|
||||
})
|
||||
}
|
||||
|
||||
// QueryCells returns the union of the member shapes' query-time coverings,
|
||||
// deduplicated and reconciled (see aggregateCells).
|
||||
func (gc *GeometryCollection) QueryCells() (inner, cross []uint64) {
|
||||
return gc.aggregateCells(func(s index.GeoJSON) ([]uint64, []uint64) {
|
||||
return s.QueryCells()
|
||||
})
|
||||
}
|
||||
|
||||
func (gc *GeometryCollection) BoundingBox() index.GeoJSON {
|
||||
r := s2.EmptyRect()
|
||||
for _, s := range gc.Shapes {
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
// every shape in this package returns its bounding box as an
|
||||
// *Envelope; members with an empty bounding box contribute an
|
||||
// empty rect, which Union ignores
|
||||
if env, ok := s.BoundingBox().(*Envelope); ok && env != nil && env.r != nil {
|
||||
r = r.Union(*env.r)
|
||||
}
|
||||
}
|
||||
return envelopeFromRect(r)
|
||||
}
|
||||
|
||||
// geometryCollectionIntersectsShape checks whether any member shape of the
|
||||
// geometrycollection intersects with the given shape.
|
||||
func geometryCollectionIntersectsShape(gc *GeometryCollection,
|
||||
shapeIn index.GeoJSON) bool {
|
||||
for _, shape := range gc.Members() {
|
||||
intersects, err := shapeIn.Intersects(shape)
|
||||
if err == nil && intersects {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (gc *GeometryCollection) UnmarshalJSON(data []byte) error {
|
||||
tmp := struct {
|
||||
Typ string `json:"type"`
|
||||
Shapes []json.RawMessage `json:"geometries"`
|
||||
}{}
|
||||
|
||||
err := jsoniter.Unmarshal(data, &tmp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gc.Typ = tmp.Typ
|
||||
|
||||
for _, shape := range tmp.Shapes {
|
||||
var t map[string]interface{}
|
||||
err := jsoniter.Unmarshal(shape, &t)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var typ string
|
||||
|
||||
if val, ok := t["type"]; ok {
|
||||
typ = strings.ToLower(val.(string))
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
|
||||
switch typ {
|
||||
case PointType:
|
||||
var p Point
|
||||
err := jsoniter.Unmarshal(shape, &p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.init()
|
||||
gc.Shapes = append(gc.Shapes, &p)
|
||||
|
||||
case MultiPointType:
|
||||
var mp MultiPoint
|
||||
err := jsoniter.Unmarshal(shape, &mp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mp.init()
|
||||
gc.Shapes = append(gc.Shapes, &mp)
|
||||
|
||||
case LineStringType:
|
||||
var ls LineString
|
||||
err := jsoniter.Unmarshal(shape, &ls)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ls.init()
|
||||
gc.Shapes = append(gc.Shapes, &ls)
|
||||
|
||||
case MultiLineStringType:
|
||||
var mls MultiLineString
|
||||
err := jsoniter.Unmarshal(shape, &mls)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mls.init()
|
||||
gc.Shapes = append(gc.Shapes, &mls)
|
||||
|
||||
case PolygonType:
|
||||
var pgn Polygon
|
||||
err := jsoniter.Unmarshal(shape, &pgn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pgn.init()
|
||||
gc.Shapes = append(gc.Shapes, &pgn)
|
||||
|
||||
case MultiPolygonType:
|
||||
var pgn MultiPolygon
|
||||
err := jsoniter.Unmarshal(shape, &pgn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pgn.init()
|
||||
gc.Shapes = append(gc.Shapes, &pgn)
|
||||
case CircleType:
|
||||
var cir Circle
|
||||
err := jsoniter.Unmarshal(shape, &cir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cir.init()
|
||||
gc.Shapes = append(gc.Shapes, &cir)
|
||||
case EnvelopeType:
|
||||
var env Envelope
|
||||
err := jsoniter.Unmarshal(shape, &env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
env.init()
|
||||
gc.Shapes = append(gc.Shapes, &env)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geojson
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/s2"
|
||||
)
|
||||
|
||||
// LineString represents the geoJSON linestring type and it
|
||||
// implements the index.GeoJSON interface.
|
||||
type LineString struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices [][]float64 `json:"coordinates"`
|
||||
pl *s2.Polyline
|
||||
}
|
||||
|
||||
// NewGeoJsonLinestring instantiates a LineString from the given coordinates.
|
||||
func NewGeoJsonLinestring(points [][]float64) index.GeoJSON {
|
||||
rv := &LineString{Typ: LineStringType, Vertices: points}
|
||||
rv.init()
|
||||
return rv
|
||||
}
|
||||
|
||||
func (ls *LineString) init() {
|
||||
if ls.pl == nil {
|
||||
latlngs := make([]s2.LatLng, len(ls.Vertices))
|
||||
for i, vertex := range ls.Vertices {
|
||||
latlngs[i] = s2.LatLngFromDegrees(vertex[1], vertex[0])
|
||||
}
|
||||
ls.pl = s2.PolylineFromLatLngs(latlngs)
|
||||
}
|
||||
}
|
||||
|
||||
func (ls *LineString) Type() string {
|
||||
return strings.ToLower(ls.Typ)
|
||||
}
|
||||
|
||||
func (ls *LineString) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(ls)
|
||||
}
|
||||
|
||||
func (ls *LineString) Marshal() ([]byte, error) {
|
||||
ls.init()
|
||||
|
||||
var b bytes.Buffer
|
||||
b.Grow(50)
|
||||
w := bufio.NewWriter(&b)
|
||||
err := ls.pl.Encode(w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return append([]byte{LineStringTypePrefix}, b.Bytes()...), nil
|
||||
}
|
||||
|
||||
func (ls *LineString) Intersects(other index.GeoJSON) (bool, error) {
|
||||
ls.init()
|
||||
|
||||
return checkLineStringsIntersectsShape([]*s2.Polyline{ls.pl}, ls, other)
|
||||
}
|
||||
|
||||
func (ls *LineString) Contains(other index.GeoJSON) (bool, error) {
|
||||
ls.init()
|
||||
return checkLineStringsContainsShape([]*s2.Polyline{ls.pl}, other)
|
||||
}
|
||||
|
||||
func (ls *LineString) Coordinates() [][]float64 {
|
||||
return ls.Vertices
|
||||
}
|
||||
|
||||
// IndexCells returns the linestring's covering: a polyline has no area, so
|
||||
// every covering cell is a cross cell and inner is always nil.
|
||||
func (ls *LineString) IndexCells() (inner, cross []uint64) {
|
||||
ls.init()
|
||||
if ls.pl == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return indexCellsFromRegion(ls.pl)
|
||||
}
|
||||
|
||||
// QueryCells returns the linestring's query-time covering; like IndexCells,
|
||||
// it can only contain cross cells.
|
||||
func (ls *LineString) QueryCells() (inner, cross []uint64) {
|
||||
ls.init()
|
||||
if ls.pl == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return queryCellsFromRegion(ls.pl)
|
||||
}
|
||||
|
||||
func (ls *LineString) BoundingBox() index.GeoJSON {
|
||||
ls.init()
|
||||
if ls.pl == nil {
|
||||
return envelopeFromRect(s2.EmptyRect())
|
||||
}
|
||||
return envelopeFromRect(ls.pl.RectBound())
|
||||
}
|
||||
|
||||
func (ls *LineString) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
ls.init()
|
||||
return StripCoveringTerms(s.GetIndexTermsForRegion(ls.pl.CapBound(), ""))
|
||||
}
|
||||
|
||||
func (ls *LineString) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
ls.init()
|
||||
return StripCoveringTerms(s.GetQueryTermsForRegion(ls.pl.CapBound(), ""))
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
// MultiLineString represents the geoJSON multilinestring type
|
||||
// and it implements the index.GeoJSON interface as well as the
|
||||
// compositeShape interface.
|
||||
type MultiLineString struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices [][][]float64 `json:"coordinates"`
|
||||
pls []*s2.Polyline
|
||||
}
|
||||
|
||||
// NewGeoJsonMultilinestring instantiates a MultiLineString from the given
|
||||
// coordinates.
|
||||
func NewGeoJsonMultilinestring(points [][][]float64) index.GeoJSON {
|
||||
rv := &MultiLineString{Typ: MultiLineStringType, Vertices: points}
|
||||
rv.init()
|
||||
return rv
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) init() {
|
||||
if mls.pls == nil {
|
||||
mls.pls = s2PolylinesFromCoordinates(mls.Vertices)
|
||||
}
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) Type() string {
|
||||
return strings.ToLower(mls.Typ)
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(mls)
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) Marshal() ([]byte, error) {
|
||||
mls.init()
|
||||
|
||||
var b bytes.Buffer
|
||||
b.Grow(256)
|
||||
w := bufio.NewWriter(&b)
|
||||
|
||||
// first write the number of linestrings.
|
||||
count := int32(len(mls.pls))
|
||||
err := binary.Write(w, binary.BigEndian, count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// write the lines.
|
||||
for _, ls := range mls.pls {
|
||||
err := ls.Encode(w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return append([]byte{MultiLineStringTypePrefix}, b.Bytes()...), nil
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) Intersects(other index.GeoJSON) (bool, error) {
|
||||
mls.init()
|
||||
return checkLineStringsIntersectsShape(mls.pls, mls, other)
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) Contains(other index.GeoJSON) (bool, error) {
|
||||
mls.init()
|
||||
return checkLineStringsContainsShape(mls.pls, other)
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) Coordinates() [][][]float64 {
|
||||
return mls.Vertices
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) Members() []index.GeoJSON {
|
||||
if len(mls.Vertices) > 0 && len(mls.pls) == 0 {
|
||||
lines := make([]index.GeoJSON, len(mls.Vertices))
|
||||
for pos, vertices := range mls.Vertices {
|
||||
lines[pos] = NewGeoJsonLinestring(vertices)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
lines := make([]index.GeoJSON, len(mls.pls))
|
||||
for pos, pl := range mls.pls {
|
||||
lines[pos] = &LineString{pl: pl}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// polylinesRegionUnion builds an s2.RegionUnion from the non-nil polylines.
|
||||
func polylinesRegionUnion(pls []*s2.Polyline) s2.RegionUnion {
|
||||
ru := make(s2.RegionUnion, 0, len(pls))
|
||||
for _, pl := range pls {
|
||||
if pl != nil {
|
||||
ru = append(ru, pl)
|
||||
}
|
||||
}
|
||||
return ru
|
||||
}
|
||||
|
||||
// IndexCells returns the multilinestring's covering, computed as a single
|
||||
// covering of the union of its polylines. Polylines have no area, so every
|
||||
// covering cell is a cross cell and inner is always nil.
|
||||
func (mls *MultiLineString) IndexCells() (inner, cross []uint64) {
|
||||
mls.init()
|
||||
ru := polylinesRegionUnion(mls.pls)
|
||||
if len(ru) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return indexCellsFromRegion(ru)
|
||||
}
|
||||
|
||||
// QueryCells returns the multilinestring's query-time covering; like
|
||||
// IndexCells, it can only contain cross cells.
|
||||
func (mls *MultiLineString) QueryCells() (inner, cross []uint64) {
|
||||
mls.init()
|
||||
ru := polylinesRegionUnion(mls.pls)
|
||||
if len(ru) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return queryCellsFromRegion(ru)
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) BoundingBox() index.GeoJSON {
|
||||
mls.init()
|
||||
r := s2.EmptyRect()
|
||||
for _, pl := range mls.pls {
|
||||
if pl != nil {
|
||||
r = r.Union(pl.RectBound())
|
||||
}
|
||||
}
|
||||
return envelopeFromRect(r)
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
mls.init()
|
||||
var rv []string
|
||||
for _, ls := range mls.pls {
|
||||
terms := s.GetIndexTermsForRegion(ls.CapBound(), "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
func (mls *MultiLineString) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
mls.init()
|
||||
|
||||
var rv []string
|
||||
for _, ls := range mls.pls {
|
||||
terms := s.GetQueryTermsForRegion(ls.CapBound(), "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
// checkLineStringsIntersectsShape checks whether the given linestrings
|
||||
// intersects with the shape in the document.
|
||||
func checkLineStringsIntersectsShape(pls []*s2.Polyline, shapeIn,
|
||||
other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
if polylineIntersectsPoint(pls, p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check the intersection for any point in the collection.
|
||||
for _, point := range p2.s2points {
|
||||
if polylineIntersectsPoint(pls, point) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a polygon.
|
||||
if p2, ok := other.(*Polygon); ok {
|
||||
if polylineIntersectsPolygons(pls, []*s2.Polygon{p2.s2pgn}) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipolygon.
|
||||
if p2, ok := other.(*MultiPolygon); ok {
|
||||
// check the intersection for any polygon in the collection.
|
||||
if polylineIntersectsPolygons(pls, p2.s2pgns) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a linestring.
|
||||
if ls, ok := other.(*LineString); ok {
|
||||
for _, pl := range pls {
|
||||
if ls.pl.Intersects(pl) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multilinestring.
|
||||
if mls, ok := other.(*MultiLineString); ok {
|
||||
for _, ls := range pls {
|
||||
for _, docLineString := range mls.pls {
|
||||
if ls.Intersects(docLineString) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if gc, ok := other.(*GeometryCollection); ok {
|
||||
// check whether the linestring intersects with any of the
|
||||
// shapes within the geometrycollection.
|
||||
if geometryCollectionIntersectsShape(gc, shapeIn) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a circle.
|
||||
if c, ok := other.(*Circle); ok {
|
||||
centre := c.s2cap.Center()
|
||||
for _, pl := range pls {
|
||||
for i := 0; i < pl.NumEdges(); i++ {
|
||||
edge := pl.Edge(i)
|
||||
distance := s2.DistanceFromSegment(centre, edge.V0, edge.V1)
|
||||
if distance <= c.s2cap.Radius() {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a envelope.
|
||||
if e, ok := other.(*Envelope); ok {
|
||||
res := rectangleIntersectsWithLineStrings(e.r, pls)
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unknown geojson type: %s "+
|
||||
"found in document", other.Type())
|
||||
}
|
||||
|
||||
// checkLineStringsContainsShape checks whether the given points or
|
||||
// multipoints lie on the linestrings (anywhere along their edges,
|
||||
// not just at the vertices).
|
||||
func checkLineStringsContainsShape(pls []*s2.Polyline,
|
||||
other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
if polylineIntersectsPoint(pls, p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check the containment for every point in the collection.
|
||||
for _, point := range p2.s2points {
|
||||
if !polylineIntersectsPoint(pls, point) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
+437
@@ -0,0 +1,437 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geojson
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/s2"
|
||||
)
|
||||
|
||||
// --------------------------------------------------------
|
||||
// Point represents the geoJSON point type and it
|
||||
// implements the index.GeoJSON interface.
|
||||
type Point struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices []float64 `json:"coordinates"`
|
||||
s2point *s2.Point
|
||||
}
|
||||
|
||||
func NewGeoJsonPoint(v []float64) index.GeoJSON {
|
||||
rv := &Point{Typ: PointType, Vertices: v}
|
||||
rv.init()
|
||||
return rv
|
||||
}
|
||||
|
||||
func (p *Point) Type() string {
|
||||
return strings.ToLower(p.Typ)
|
||||
}
|
||||
|
||||
func (p *Point) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(p)
|
||||
}
|
||||
|
||||
func (p *Point) init() {
|
||||
if p.s2point == nil {
|
||||
s2point := s2.PointFromLatLng(s2.LatLngFromDegrees(
|
||||
p.Vertices[1], p.Vertices[0]))
|
||||
p.s2point = &s2point
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Point) Marshal() ([]byte, error) {
|
||||
p.init()
|
||||
|
||||
var b bytes.Buffer
|
||||
b.Grow(32)
|
||||
w := bufio.NewWriter(&b)
|
||||
err := p.s2point.Encode(w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return append([]byte{PointTypePrefix}, b.Bytes()...), nil
|
||||
}
|
||||
|
||||
func (p *Point) Intersects(other index.GeoJSON) (bool, error) {
|
||||
p.init()
|
||||
|
||||
return checkPointIntersectsShape(p.s2point, p, other)
|
||||
}
|
||||
|
||||
func (p *Point) Contains(other index.GeoJSON) (bool, error) {
|
||||
p.init()
|
||||
|
||||
return checkPointContainsShape([]*s2.Point{p.s2point}, other)
|
||||
}
|
||||
|
||||
func (p *Point) Coordinates() []float64 {
|
||||
return p.Vertices
|
||||
}
|
||||
|
||||
// IndexCells returns the point's covering: a point has no area, so it is a
|
||||
// single maxCellLevel cross cell and never an inner cell.
|
||||
func (p *Point) IndexCells() (inner, cross []uint64) {
|
||||
p.init()
|
||||
if p.s2point == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, []uint64{pointCell(*p.s2point)}
|
||||
}
|
||||
|
||||
// QueryCells delegates to IndexCells: a point maps to exactly one cell, so
|
||||
// the query-time coverer would produce the same single cross cell as the
|
||||
// index-time coverer.
|
||||
func (p *Point) QueryCells() (inner, cross []uint64) {
|
||||
return p.IndexCells()
|
||||
}
|
||||
|
||||
func (p *Point) BoundingBox() index.GeoJSON {
|
||||
p.init()
|
||||
if p.s2point == nil {
|
||||
return envelopeFromRect(s2.EmptyRect())
|
||||
}
|
||||
return envelopeFromRect(p.s2point.RectBound())
|
||||
}
|
||||
|
||||
func (p *Point) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
p.init()
|
||||
terms := s.GetIndexTermsForPoint(*p.s2point, "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
func (p *Point) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
p.init()
|
||||
terms := s.GetQueryTermsForPoint(*p.s2point, "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
// MultiPoint represents the geoJSON multipoint type and it
|
||||
// implements the index.GeoJSON interface as well as the
|
||||
// compositeShape interface.
|
||||
type MultiPoint struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices [][]float64 `json:"coordinates"`
|
||||
s2points []*s2.Point
|
||||
}
|
||||
|
||||
func NewGeoJsonMultiPoint(v [][]float64) index.GeoJSON {
|
||||
rv := &MultiPoint{Typ: MultiPointType, Vertices: v}
|
||||
rv.init()
|
||||
return rv
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) init() {
|
||||
if mp.s2points == nil {
|
||||
mp.s2points = make([]*s2.Point, len(mp.Vertices))
|
||||
for i, point := range mp.Vertices {
|
||||
s2point := s2.PointFromLatLng(s2.LatLngFromDegrees(
|
||||
point[1], point[0]))
|
||||
mp.s2points[i] = &s2point
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) Marshal() ([]byte, error) {
|
||||
mp.init()
|
||||
|
||||
var b bytes.Buffer
|
||||
b.Grow(64)
|
||||
w := bufio.NewWriter(&b)
|
||||
|
||||
// first write the number of points.
|
||||
count := int32(len(mp.s2points))
|
||||
err := binary.Write(w, binary.BigEndian, count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// write the points.
|
||||
for _, s2point := range mp.s2points {
|
||||
err := s2point.Encode(w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return append([]byte{MultiPointTypePrefix}, b.Bytes()...), nil
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) Type() string {
|
||||
return strings.ToLower(mp.Typ)
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(mp)
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) Intersects(other index.GeoJSON) (bool, error) {
|
||||
mp.init()
|
||||
|
||||
for _, s2point := range mp.s2points {
|
||||
rv, err := checkPointIntersectsShape(s2point, mp, other)
|
||||
if rv && err == nil {
|
||||
return rv, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) Contains(other index.GeoJSON) (bool, error) {
|
||||
mp.init()
|
||||
|
||||
rv, err := checkPointContainsShape(mp.s2points, other)
|
||||
if rv && err == nil {
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) Coordinates() [][]float64 {
|
||||
return mp.Vertices
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) Members() []index.GeoJSON {
|
||||
if len(mp.Vertices) > 0 && len(mp.s2points) == 0 {
|
||||
points := make([]index.GeoJSON, len(mp.Vertices))
|
||||
for pos, vertices := range mp.Vertices {
|
||||
points[pos] = NewGeoJsonPoint(vertices)
|
||||
}
|
||||
return points
|
||||
}
|
||||
|
||||
points := make([]index.GeoJSON, len(mp.s2points))
|
||||
for pos, point := range mp.s2points {
|
||||
points[pos] = &Point{s2point: point}
|
||||
}
|
||||
return points
|
||||
}
|
||||
|
||||
// IndexCells returns the multipoint's covering: points have no area, so the
|
||||
// result is one maxCellLevel cross cell per distinct point cell and never any
|
||||
// inner cells. Cells are deduplicated, since points can share a cell.
|
||||
func (mp *MultiPoint) IndexCells() (inner, cross []uint64) {
|
||||
mp.init()
|
||||
seen := make(map[uint64]struct{}, len(mp.s2points))
|
||||
cross = make([]uint64, 0, len(mp.s2points))
|
||||
for _, pt := range mp.s2points {
|
||||
if pt == nil {
|
||||
continue
|
||||
}
|
||||
cell := pointCell(*pt)
|
||||
if _, ok := seen[cell]; ok {
|
||||
continue
|
||||
}
|
||||
seen[cell] = struct{}{}
|
||||
cross = append(cross, cell)
|
||||
}
|
||||
return nil, cross
|
||||
}
|
||||
|
||||
// QueryCells delegates to IndexCells: each point maps to exactly one cell, so
|
||||
// the query-time coverer would produce the same cross cells as the index-time
|
||||
// coverer.
|
||||
func (mp *MultiPoint) QueryCells() (inner, cross []uint64) {
|
||||
return mp.IndexCells()
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) BoundingBox() index.GeoJSON {
|
||||
mp.init()
|
||||
r := s2.EmptyRect()
|
||||
for _, pt := range mp.s2points {
|
||||
if pt == nil {
|
||||
continue
|
||||
}
|
||||
r = r.Union(pt.RectBound())
|
||||
}
|
||||
return envelopeFromRect(r)
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
mp.init()
|
||||
var rv []string
|
||||
for _, s2point := range mp.s2points {
|
||||
terms := s.GetIndexTermsForPoint(*s2point, "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
func (mp *MultiPoint) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
mp.init()
|
||||
var rv []string
|
||||
for _, s2point := range mp.s2points {
|
||||
terms := s.GetQueryTermsForPoint(*s2point, "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
// checkPointIntersectsShape checks for intersection between
|
||||
// the point and the shape in the document.
|
||||
func checkPointIntersectsShape(point *s2.Point, shapeIn, other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
// check if the points are equal
|
||||
if point.ApproxEqual(*p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check if any of the points are equal
|
||||
for _, p := range p2.s2points {
|
||||
if point.ApproxEqual(*p) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a polygon.
|
||||
if p2, ok := other.(*Polygon); ok {
|
||||
// check if the point is contained within the polygon.
|
||||
if polygonsIntersectsPoint([]*s2.Polygon{p2.s2pgn}, point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipolygon.
|
||||
if p2, ok := other.(*MultiPolygon); ok {
|
||||
// check if the point is contained within any of the polygons
|
||||
if polygonsIntersectsPoint(p2.s2pgns, point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a linestring.
|
||||
if p2, ok := other.(*LineString); ok {
|
||||
// project the point to the linestring and check if
|
||||
// the projection is equal to the point.
|
||||
if polylineIntersectsPoint([]*s2.Polyline{p2.pl}, point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multilinestring.
|
||||
if p2, ok := other.(*MultiLineString); ok {
|
||||
// check the intersection for any linestring in the array.
|
||||
if polylineIntersectsPoint(p2.pls, point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a geometrycollection.
|
||||
if gc, ok := other.(*GeometryCollection); ok {
|
||||
// check for intersection across every member shape.
|
||||
if geometryCollectionIntersectsShape(gc, shapeIn) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a circle.
|
||||
if c, ok := other.(*Circle); ok {
|
||||
// check if the point is contained within the circle
|
||||
// by calculating the distance between the point and the
|
||||
// center of the circle.
|
||||
if c.s2cap.ContainsPoint(*point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is an envelope.
|
||||
if e, ok := other.(*Envelope); ok {
|
||||
// check if the point is contained by the envelope
|
||||
// by checking if the point is within its bounds
|
||||
if e.r.ContainsPoint(*point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unknown geojson type: %s "+
|
||||
" found in document", other.Type())
|
||||
}
|
||||
|
||||
// checkPointContainsShape checks whether the given shape in
|
||||
// in the document is approximately contained with the point.
|
||||
func checkPointContainsShape(points []*s2.Point,
|
||||
other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
for _, point := range points {
|
||||
if point.ApproxEqual(*p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint, if so containment is
|
||||
// checked for every point in the multipoint with every given point.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check the containment for every point in the collection.
|
||||
lookup := make(map[int]struct{})
|
||||
for _, qpoint := range points {
|
||||
for pos, dpoint := range p2.s2points {
|
||||
if _, done := lookup[pos]; done {
|
||||
continue
|
||||
}
|
||||
// already processed all the points in the multipoint.
|
||||
if len(lookup) == len(p2.s2points) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
if qpoint.ApproxEqual(*dpoint) {
|
||||
lookup[pos] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return len(lookup) == len(p2.s2points), nil
|
||||
}
|
||||
|
||||
// as point is a non closed shape, containment isn't feasible
|
||||
// for other higher dimensions.
|
||||
return false, nil
|
||||
}
|
||||
+543
@@ -0,0 +1,543 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package geojson
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/blevesearch/geo/s2"
|
||||
)
|
||||
|
||||
// Polygon represents the geoJSON polygon type
|
||||
// and it implements the index.GeoJSON interface.
|
||||
type Polygon struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices [][][]float64 `json:"coordinates"`
|
||||
s2pgn *s2.Polygon
|
||||
}
|
||||
|
||||
func NewGeoJsonPolygon(points [][][]float64) index.GeoJSON {
|
||||
rv := &Polygon{Typ: PolygonType, Vertices: points}
|
||||
rv.init()
|
||||
return rv
|
||||
}
|
||||
|
||||
func (pg *Polygon) init() {
|
||||
if pg.s2pgn == nil {
|
||||
pg.s2pgn = s2PolygonFromCoordinates(pg.Vertices)
|
||||
}
|
||||
}
|
||||
|
||||
func (pg *Polygon) Type() string {
|
||||
return strings.ToLower(pg.Typ)
|
||||
}
|
||||
|
||||
func (pg *Polygon) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(pg)
|
||||
}
|
||||
|
||||
func (pg *Polygon) Marshal() ([]byte, error) {
|
||||
pg.init()
|
||||
|
||||
var b bytes.Buffer
|
||||
b.Grow(128)
|
||||
w := bufio.NewWriter(&b)
|
||||
err := pg.s2pgn.Encode(w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return append([]byte{PolygonTypePrefix}, b.Bytes()...), nil
|
||||
}
|
||||
|
||||
func (pg *Polygon) Intersects(other index.GeoJSON) (bool, error) {
|
||||
// lazily build the s2polygon for reuse.
|
||||
pg.init()
|
||||
|
||||
return checkPolygonIntersectsShape(pg.s2pgn, pg, other)
|
||||
}
|
||||
|
||||
func (pg *Polygon) Contains(other index.GeoJSON) (bool, error) {
|
||||
// lazily build the s2polygon for reuse.
|
||||
pg.init()
|
||||
|
||||
return checkMultiPolygonContainsShape([]*s2.Polygon{pg.s2pgn}, pg, other)
|
||||
}
|
||||
|
||||
func (pg *Polygon) Coordinates() [][][]float64 {
|
||||
return pg.Vertices
|
||||
}
|
||||
|
||||
// IndexCells returns the polygon's covering partitioned into inner cells
|
||||
// (fully contained in the polygon, excluding any holes) and cross cells
|
||||
// (overlapping the boundary). The hole exclusion relies on the s2 polygon
|
||||
// being built from oriented loops, so ContainsCell is false for cells
|
||||
// inside interior rings.
|
||||
func (pg *Polygon) IndexCells() (inner, cross []uint64) {
|
||||
pg.init()
|
||||
if pg.s2pgn == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return indexCellsFromRegion(pg.s2pgn)
|
||||
}
|
||||
|
||||
// QueryCells returns the polygon's query-time covering, partitioned the same
|
||||
// way as IndexCells.
|
||||
func (pg *Polygon) QueryCells() (inner, cross []uint64) {
|
||||
pg.init()
|
||||
if pg.s2pgn == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return queryCellsFromRegion(pg.s2pgn)
|
||||
}
|
||||
|
||||
func (pg *Polygon) BoundingBox() index.GeoJSON {
|
||||
pg.init()
|
||||
if pg.s2pgn == nil {
|
||||
return envelopeFromRect(s2.EmptyRect())
|
||||
}
|
||||
return envelopeFromRect(pg.s2pgn.RectBound())
|
||||
}
|
||||
|
||||
func (pg *Polygon) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
pg.init()
|
||||
terms := s.GetIndexTermsForRegion(
|
||||
pg.s2pgn.CapBound(), "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
func (pg *Polygon) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
pg.init()
|
||||
terms := s.GetQueryTermsForRegion(
|
||||
pg.s2pgn.CapBound(), "")
|
||||
return StripCoveringTerms(terms)
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
// MultiPolygon represents the geoJSON multipolygon type
|
||||
// and it implements the index.GeoJSON interface as well as the
|
||||
// compositeShape interface.
|
||||
type MultiPolygon struct {
|
||||
Typ string `json:"type"`
|
||||
Vertices [][][][]float64 `json:"coordinates"`
|
||||
s2pgns []*s2.Polygon
|
||||
}
|
||||
|
||||
func NewGeoJsonMultiPolygon(points [][][][]float64) index.GeoJSON {
|
||||
rv := &MultiPolygon{Typ: MultiPolygonType, Vertices: points}
|
||||
rv.init()
|
||||
return rv
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) init() {
|
||||
if mp.s2pgns == nil {
|
||||
mp.s2pgns = make([]*s2.Polygon, len(mp.Vertices))
|
||||
for i, vertices := range mp.Vertices {
|
||||
pgn := s2PolygonFromCoordinates(vertices)
|
||||
mp.s2pgns[i] = pgn
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) Type() string {
|
||||
return strings.ToLower(mp.Typ)
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) Value() ([]byte, error) {
|
||||
return jsoniter.Marshal(mp)
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) Marshal() ([]byte, error) {
|
||||
mp.init()
|
||||
|
||||
var b bytes.Buffer
|
||||
b.Grow(512)
|
||||
w := bufio.NewWriter(&b)
|
||||
|
||||
// first write the number of polygons.
|
||||
count := int32(len(mp.s2pgns))
|
||||
err := binary.Write(w, binary.BigEndian, count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// write the polygons.
|
||||
for _, pgn := range mp.s2pgns {
|
||||
err := pgn.Encode(w)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return append([]byte{MultiPolygonTypePrefix}, b.Bytes()...), nil
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) Intersects(other index.GeoJSON) (bool, error) {
|
||||
mp.init()
|
||||
|
||||
for _, pgn := range mp.s2pgns {
|
||||
rv, err := checkPolygonIntersectsShape(pgn, mp, other)
|
||||
if rv && err == nil {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) Contains(other index.GeoJSON) (bool, error) {
|
||||
mp.init()
|
||||
|
||||
return checkMultiPolygonContainsShape(mp.s2pgns, mp, other)
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) Coordinates() [][][][]float64 {
|
||||
return mp.Vertices
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) Members() []index.GeoJSON {
|
||||
if len(mp.Vertices) > 0 && len(mp.s2pgns) == 0 {
|
||||
polygons := make([]index.GeoJSON, len(mp.Vertices))
|
||||
for pos, vertices := range mp.Vertices {
|
||||
polygons[pos] = NewGeoJsonPolygon(vertices)
|
||||
}
|
||||
return polygons
|
||||
}
|
||||
|
||||
polygons := make([]index.GeoJSON, len(mp.s2pgns))
|
||||
for pos, pgn := range mp.s2pgns {
|
||||
polygons[pos] = &Polygon{s2pgn: pgn}
|
||||
}
|
||||
return polygons
|
||||
}
|
||||
|
||||
// polygonsRegionUnion builds an s2.RegionUnion from the non-nil polygons.
|
||||
func polygonsRegionUnion(pgns []*s2.Polygon) s2.RegionUnion {
|
||||
ru := make(s2.RegionUnion, 0, len(pgns))
|
||||
for _, pg := range pgns {
|
||||
if pg != nil {
|
||||
ru = append(ru, pg)
|
||||
}
|
||||
}
|
||||
return ru
|
||||
}
|
||||
|
||||
// IndexCells returns the multipolygon's covering, computed as a single
|
||||
// covering of the union of its polygons and partitioned into inner and
|
||||
// cross cells.
|
||||
func (mp *MultiPolygon) IndexCells() (inner, cross []uint64) {
|
||||
mp.init()
|
||||
ru := polygonsRegionUnion(mp.s2pgns)
|
||||
if len(ru) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return indexCellsFromRegion(ru)
|
||||
}
|
||||
|
||||
// QueryCells returns the multipolygon's query-time covering, partitioned the
|
||||
// same way as IndexCells.
|
||||
func (mp *MultiPolygon) QueryCells() (inner, cross []uint64) {
|
||||
mp.init()
|
||||
ru := polygonsRegionUnion(mp.s2pgns)
|
||||
if len(ru) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return queryCellsFromRegion(ru)
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) BoundingBox() index.GeoJSON {
|
||||
mp.init()
|
||||
r := s2.EmptyRect()
|
||||
for _, pg := range mp.s2pgns {
|
||||
if pg != nil {
|
||||
r = r.Union(pg.RectBound())
|
||||
}
|
||||
}
|
||||
return envelopeFromRect(r)
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) IndexTokens(s *s2.RegionTermIndexer) []string {
|
||||
mp.init()
|
||||
|
||||
var rv []string
|
||||
for _, s2pgn := range mp.s2pgns {
|
||||
terms := s.GetIndexTermsForRegion(s2pgn.CapBound(), "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
func (mp *MultiPolygon) QueryTokens(s *s2.RegionTermIndexer) []string {
|
||||
mp.init()
|
||||
|
||||
var rv []string
|
||||
for _, s2pgn := range mp.s2pgns {
|
||||
terms := s.GetQueryTermsForRegion(s2pgn.CapBound(), "")
|
||||
rv = append(rv, terms...)
|
||||
}
|
||||
|
||||
return StripCoveringTerms(rv)
|
||||
}
|
||||
|
||||
// checkPolygonIntersectsShape checks the intersection between the
|
||||
// s2 polygon and the other shapes in the documents.
|
||||
func checkPolygonIntersectsShape(s2pgn *s2.Polygon, shapeIn,
|
||||
other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
if polygonsIntersectsPoint([]*s2.Polygon{s2pgn}, p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
for _, s2point := range p2.s2points {
|
||||
if polygonsIntersectsPoint([]*s2.Polygon{s2pgn}, s2point) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a polygon.
|
||||
if p2, ok := other.(*Polygon); ok {
|
||||
if s2pgn.Intersects(p2.s2pgn) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipolygon.
|
||||
if p2, ok := other.(*MultiPolygon); ok {
|
||||
// check the intersection for any polygon in the collection.
|
||||
for _, s2pgn1 := range p2.s2pgns {
|
||||
if s2pgn.Intersects(s2pgn1) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a linestring.
|
||||
if ls, ok := other.(*LineString); ok {
|
||||
if polylineIntersectsPolygons([]*s2.Polyline{ls.pl},
|
||||
[]*s2.Polygon{s2pgn}) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multilinestring.
|
||||
if mls, ok := other.(*MultiLineString); ok {
|
||||
if polylineIntersectsPolygons(mls.pls, []*s2.Polygon{s2pgn}) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if gc, ok := other.(*GeometryCollection); ok {
|
||||
// check whether the polygon intersects with any of the
|
||||
// member shapes of the geometry collection.
|
||||
if geometryCollectionIntersectsShape(gc, shapeIn) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a circle.
|
||||
if c, ok := other.(*Circle); ok {
|
||||
cp := c.s2cap.Center()
|
||||
radius := c.s2cap.Radius()
|
||||
|
||||
projected := s2pgn.Project(&cp)
|
||||
distance := projected.Distance(cp)
|
||||
|
||||
return distance <= radius, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a envelope.
|
||||
if e, ok := other.(*Envelope); ok {
|
||||
s2pgnInDoc := s2PolygonFromS2Rectangle(e.r)
|
||||
if s2pgn.Intersects(s2pgnInDoc) {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unknown geojson type: %s "+
|
||||
" found in document", other.Type())
|
||||
}
|
||||
|
||||
// checkMultiPolygonContainsShape checks whether the given polygons
|
||||
// collectively contains the shape in the document.
|
||||
func checkMultiPolygonContainsShape(s2pgns []*s2.Polygon,
|
||||
shapeIn, other index.GeoJSON) (bool, error) {
|
||||
// check if the other shape is a point.
|
||||
if p2, ok := other.(*Point); ok {
|
||||
if polygonsIntersectsPoint(s2pgns, p2.s2point) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipoint.
|
||||
if p2, ok := other.(*MultiPoint); ok {
|
||||
// check the containment for every point in the collection.
|
||||
idx := s2.NewShapeIndex()
|
||||
for _, s2pgn := range s2pgns {
|
||||
idx.Add(s2pgn)
|
||||
}
|
||||
|
||||
for _, point := range p2.s2points {
|
||||
if !s2.NewContainsPointQuery(idx, s2.VertexModelClosed).Contains(*point) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a polygon.
|
||||
if p2, ok := other.(*Polygon); ok {
|
||||
for _, s2pgn := range s2pgns {
|
||||
if s2pgn.Contains(p2.s2pgn) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multipolygon.
|
||||
if p2, ok := other.(*MultiPolygon); ok {
|
||||
// check the intersection for every polygon in the collection.
|
||||
polygonsWithIn := make(map[int]struct{})
|
||||
nextPolygon:
|
||||
for pgnIndex, pgn := range p2.s2pgns {
|
||||
for _, s2pgn := range s2pgns {
|
||||
if s2pgn.Contains(pgn) {
|
||||
polygonsWithIn[pgnIndex] = struct{}{}
|
||||
continue nextPolygon
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return len(p2.s2pgns) == len(polygonsWithIn), nil
|
||||
}
|
||||
|
||||
// check if the other shape is a linestring.
|
||||
if ls, ok := other.(*LineString); ok {
|
||||
if polygonsContainsLineStrings(s2pgns,
|
||||
[]*s2.Polyline{ls.pl}) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a multilinestring.
|
||||
if mls, ok := other.(*MultiLineString); ok {
|
||||
// check whether any of the linestring is inside the polygon.
|
||||
if polygonsContainsLineStrings(s2pgns, mls.pls) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if gc, ok := other.(*GeometryCollection); ok {
|
||||
shapesWithIn := make(map[int]struct{})
|
||||
nextShape:
|
||||
for pos, shape := range gc.Members() {
|
||||
for _, s2pgn := range s2pgns {
|
||||
contains, err := checkMultiPolygonContainsShape(
|
||||
[]*s2.Polygon{s2pgn}, shapeIn, shape)
|
||||
if err == nil && contains {
|
||||
shapesWithIn[pos] = struct{}{}
|
||||
continue nextShape
|
||||
}
|
||||
}
|
||||
}
|
||||
return len(shapesWithIn) == len(gc.Members()), nil
|
||||
}
|
||||
|
||||
// check if the other shape is a circle.
|
||||
if c, ok := other.(*Circle); ok {
|
||||
cp := c.s2cap.Center()
|
||||
radius := c.s2cap.Radius()
|
||||
|
||||
for _, s2pgn := range s2pgns {
|
||||
if s2pgn == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// The full polygon covers the sphere, so it contains every circle,
|
||||
// but it carries no boundary edges to measure the radius against.
|
||||
if s2pgn.IsFull() {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Any other polygon without boundary edges is degenerate: it
|
||||
// encloses no area, so it cannot contain a circle, and there is no
|
||||
// boundary to project the centre onto.
|
||||
if s2pgn.NumEdges() == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if s2pgn.ContainsPoint(cp) {
|
||||
projected := s2pgn.ProjectToBoundary(&cp)
|
||||
distance := projected.Distance(cp)
|
||||
if distance >= radius {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if the other shape is a envelope.
|
||||
if e, ok := other.(*Envelope); ok {
|
||||
// create a polygon from the rectangle and checks the containment.
|
||||
s2pgnInDoc := s2PolygonFromS2Rectangle(e.r)
|
||||
for _, s2pgn := range s2pgns {
|
||||
if s2pgn.Contains(s2pgnInDoc) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unknown geojson type: %s"+
|
||||
" found in document", other.Type())
|
||||
}
|
||||
+14
-1
@@ -591,9 +591,15 @@ func (p *Polygon) RectBound() Rect { return p.bound }
|
||||
|
||||
// ContainsPoint reports whether the polygon contains the point.
|
||||
func (p *Polygon) ContainsPoint(point Point) bool {
|
||||
// The full polygon contains every point, and initEdgesAndIndex leaves it
|
||||
// without a ShapeIndex, so answer it before any index access below.
|
||||
if p.IsFull() {
|
||||
return true
|
||||
}
|
||||
|
||||
// NOTE: A bounds check slows down this function by about 50%. It is
|
||||
// worthwhile only when it might allow us to delay building the index.
|
||||
if !p.index.IsFresh() && !p.bound.ContainsPoint(point) {
|
||||
if (p.index == nil || !p.index.IsFresh()) && !p.bound.ContainsPoint(point) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -1238,10 +1244,17 @@ func (p *Polygon) Project(point *Point) Point {
|
||||
}
|
||||
|
||||
func (p *Polygon) ProjectToBoundary(point *Point) Point {
|
||||
if p.index == nil || p.NumEdges() == 0 {
|
||||
return *point
|
||||
}
|
||||
|
||||
options := NewClosestEdgeQueryOptions().MaxResults(1).IncludeInteriors(false)
|
||||
q := NewClosestEdgeQuery(p.index, options)
|
||||
target := NewMinDistanceToPointTarget(*point)
|
||||
edges := q.FindEdges(target)
|
||||
if len(edges) == 0 {
|
||||
return *point
|
||||
}
|
||||
return q.Project(*point, edges[0])
|
||||
}
|
||||
|
||||
|
||||
+5
@@ -11,6 +11,11 @@ First you will need to build and install Faiss:
|
||||
```
|
||||
git clone https://github.com/blevesearch/faiss.git
|
||||
cd faiss
|
||||
# Install minimal build dependencies
|
||||
# Ubuntu/Debian based systems: apt-get install libblas-dev liblapack-dev swig build-essential
|
||||
|
||||
export Python_INCLUDE_DIRS=<PYTHON_INSTALLED_DIR>/include
|
||||
export Python_LIBRARIES=<PYTHON_INSTALLED_DIR>/lib/libpython3.so
|
||||
cmake -B build -DFAISS_ENABLE_GPU=OFF -DFAISS_ENABLE_C_API=ON -DBUILD_SHARED_LIBS=ON .
|
||||
make -C build
|
||||
sudo make -C build install
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@ type ParameterSpace struct {
|
||||
func NewParameterSpace() (*ParameterSpace, error) {
|
||||
var ps *C.FaissParameterSpace
|
||||
if c := C.faiss_ParameterSpace_new(&ps); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateParamsFailed, getLastError(), int(c))
|
||||
}
|
||||
return &ParameterSpace{ps}, nil
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func (p *ParameterSpace) SetIndexParameter(idx Index, name string, val float64)
|
||||
c := C.faiss_ParameterSpace_set_index_parameter(
|
||||
p.ps, idx.cPtr(), cname, C.double(val))
|
||||
if c != 0 {
|
||||
return getLastError()
|
||||
return newFaissError(ErrSetParamsFailed, getLastError(), int(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package faiss
|
||||
|
||||
/*
|
||||
#include <faiss/c_api/error_c.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// faissError wraps an error returned by a faiss C API call,
|
||||
// including the error type and the error code returned by the C API.
|
||||
type faissError struct {
|
||||
errType error
|
||||
err error
|
||||
errCode int
|
||||
}
|
||||
|
||||
func (e *faissError) Error() string {
|
||||
return fmt.Sprintf("faiss %s: %s (code %d)", e.errType, e.err, e.errCode)
|
||||
}
|
||||
|
||||
// returns the error type which can allow usage of
|
||||
// errors.Is and errors.As for error handling.
|
||||
func (e *faissError) Unwrap() error {
|
||||
return e.errType
|
||||
}
|
||||
|
||||
// create a new faissError with the given error type, underlying error, and error code.
|
||||
func newFaissError(errType, err error, errCode int) error {
|
||||
return &faissError{
|
||||
errType: errType,
|
||||
err: err,
|
||||
errCode: errCode,
|
||||
}
|
||||
}
|
||||
|
||||
// FAISS error types for categorizing errors returned by the C API.
|
||||
var (
|
||||
// ---- Construction ----
|
||||
|
||||
ErrCreateIndexFailed = errors.New("create index failed")
|
||||
ErrCreateSelectorFailed = errors.New("create selector failed")
|
||||
|
||||
// ---- Configuration ----
|
||||
|
||||
ErrCreateParamsFailed = errors.New("create search params failed")
|
||||
ErrSetParamsFailed = errors.New("set index params failed")
|
||||
|
||||
// ---- Vector ops ----
|
||||
|
||||
ErrAddFailed = errors.New("add vectors failed")
|
||||
ErrTrainFailed = errors.New("train index failed")
|
||||
ErrSearchFailed = errors.New("search index failed")
|
||||
ErrReconstructFailed = errors.New("reconstruct vector failed")
|
||||
ErrResetIndexFailed = errors.New("reset index failed")
|
||||
ErrSetQuantizerFailed = errors.New("set quantizer failed")
|
||||
ErrMergeFromFailed = errors.New("merge from index failed")
|
||||
ErrRemoveIDsFailed = errors.New("remove IDs failed")
|
||||
|
||||
// ---- Read-only index introspection ----
|
||||
|
||||
ErrInspectIndexFailed = errors.New("inspect index failed")
|
||||
|
||||
// ---- I/O ----
|
||||
|
||||
ErrWriteIndexFailed = errors.New("write index failed")
|
||||
ErrReadIndexFailed = errors.New("read index failed")
|
||||
|
||||
// ---- GPU ----
|
||||
|
||||
ErrNoUsableGPUDevices = errors.New("no GPU usable devices available")
|
||||
ErrGPUCloneFailed = errors.New("GPU clone failed")
|
||||
ErrGPUSetupFailed = errors.New("GPU setup failed")
|
||||
ErrGPUContextFailed = errors.New("GPU context init failed")
|
||||
ErrGPUOutOfMemory = errors.New("GPU out of memory")
|
||||
|
||||
// ---- State / pre-condition errors ----
|
||||
|
||||
ErrIndexNil = errors.New("index is nil")
|
||||
ErrSelectorNil = errors.New("selector is nil")
|
||||
ErrNotIDMapIndex = errors.New("index is not an IDMap index")
|
||||
ErrNotIVFIndex = errors.New("index is not an IVF index")
|
||||
ErrNotBIVFIndex = errors.New("index is not a binary IVF index")
|
||||
|
||||
// ---- Unsupported operations ----
|
||||
|
||||
ErrMergeFromNotSupported = errors.New("merge from is not supported for this index type")
|
||||
ErrSetQuantizerNotSupported = errors.New("set quantizer not supported for this index type")
|
||||
)
|
||||
|
||||
// getLastError returns the last error message set by the FAISS C API.
|
||||
//
|
||||
// The underlying C variable is thread-local / global and can be clobbered
|
||||
// by concurrent FAISS calls or by goroutine rescheduling across OS threads,
|
||||
// so this string is best-effort diagnostic context only. Always use the
|
||||
// errType sentinel (with errors.Is / errors.As) to identify the error.
|
||||
func getLastError() error {
|
||||
return errors.New(C.GoString(C.faiss_get_last_error()))
|
||||
}
|
||||
+16
-16
@@ -8,18 +8,10 @@ package faiss
|
||||
#cgo LDFLAGS: -lfaiss_c
|
||||
|
||||
#include <faiss/c_api/Index_c.h>
|
||||
#include <faiss/c_api/error_c.h>
|
||||
#include <faiss/c_api/utils/distances_c.h>
|
||||
#include <faiss/c_api/utils/utils_c.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func getLastError() error {
|
||||
return errors.New(C.GoString(C.faiss_get_last_error()))
|
||||
}
|
||||
|
||||
// Metric type
|
||||
const (
|
||||
@@ -43,10 +35,18 @@ func NormalizeVector(vector []float32) []float32 {
|
||||
return vector
|
||||
}
|
||||
|
||||
var (
|
||||
errNotIVFIndex = fmt.Errorf("index is not of ivf type")
|
||||
errMergeFromNotSupported = fmt.Errorf("merge api not supported")
|
||||
errNotBIVFIndex = fmt.Errorf("index is not of bivf type")
|
||||
errFailedToSetQuantizers = fmt.Errorf("couldn't set the quantizers")
|
||||
errSourceIndexNil = fmt.Errorf("source index is nil")
|
||||
)
|
||||
// RealToBinary converts n real-valued vectors into binary vectors.
|
||||
// Each output bit is 1 if the corresponding input value is > 0,
|
||||
// and 0 otherwise. d must be a multiple of 8.
|
||||
// The returned slice has length n * (d / 8).
|
||||
func RealToBinary(x []float32, d int) []uint8 {
|
||||
n := len(x) / d
|
||||
out := make([]uint8, n*(d/8))
|
||||
C.faiss_real_to_binary(
|
||||
C.size_t(n),
|
||||
C.size_t(d),
|
||||
(*C.float)(&x[0]),
|
||||
(*C.uint8_t)(&out[0]),
|
||||
)
|
||||
return out
|
||||
}
|
||||
+665
-180
@@ -13,6 +13,7 @@
|
||||
// limitations under the License.
|
||||
|
||||
//go:build gpu
|
||||
// +build gpu
|
||||
|
||||
package faiss
|
||||
|
||||
@@ -22,23 +23,18 @@ package faiss
|
||||
#include <faiss/c_api/gpu/GpuAutoTune_c.h>
|
||||
#include <faiss/c_api/gpu/GpuClonerOptions_c.h>
|
||||
#include <faiss/c_api/gpu/DeviceUtils_c.h>
|
||||
#include <faiss/c_api/gpu/GpuIndex_c_ex.h>
|
||||
#include <faiss/c_api/gpu/GpuIndexIVF_c_ex.h>
|
||||
#include <faiss/c_api/gpu/GpuMemoryEstimate_c.h>
|
||||
#include <faiss/c_api/gpu/GpuMemoryPool_c.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
errAccessingGPUDevices = errors.New("error accessing GPU devices")
|
||||
errNilIndex = errors.New("index is nil")
|
||||
errNoGPUDevices = errors.New("no GPU devices available")
|
||||
)
|
||||
|
||||
// memorySpace controls where GPU index data is allocated.
|
||||
@@ -53,30 +49,50 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
// the minimum amount of free memory that must be available on a GPU to be considered for index cloning.
|
||||
minGPUFreeMemory = 512 * 1024 * 1024 // 512 MiB
|
||||
// the default memory space to use for GPU indices
|
||||
defaultGPUMemoryMode = memorySpaceUnified
|
||||
// reserve atleast 10% of total GPU memory for the the memory pool.
|
||||
defaultGPUPoolBudget = 0.1
|
||||
// reserve 8MB of GPU memory for temporary buffer _per_ GPU index.
|
||||
// NOTE: This number must be divisible by 1024.
|
||||
// CAUTION: Setting this number too high can result in degraded performance as we we may end up
|
||||
// reducing the total number of vector indexes in the GPU as a whole.
|
||||
defaultGPUTempMemorySize = 8 * 1024 * 1024
|
||||
// use device memory by default since we already do memory estimation and reservation in our GPU snapshot store.
|
||||
defaultGPUMemoryMode = memorySpaceDevice
|
||||
// disable pinned memory by default to avoid exhausting CPU memory when cloning multiple indexes to GPU.
|
||||
defaultGPUPinnedMemory = 0
|
||||
// refresh the order in which GPUs are assigned every 500ms.
|
||||
defaultGPULoadBalancerInterval = 500 * time.Millisecond
|
||||
)
|
||||
|
||||
var (
|
||||
gpuCount int
|
||||
loadBalancer *gpuLoadBalancer
|
||||
gpuCount int
|
||||
loadBalancer *gpuLoadBalancer
|
||||
snapshotStore *gpuSnapshotStore
|
||||
memoryPoolStore *gpuMemoryPoolStore
|
||||
|
||||
reflectStaticSizeFaissGPUIndex uint64
|
||||
)
|
||||
|
||||
// --------------------------------
|
||||
// GPU Setup
|
||||
// --------------------------------
|
||||
|
||||
func init() {
|
||||
var g faissGPUIndex
|
||||
reflectStaticSizeFaissGPUIndex = uint64(reflect.TypeOf(g).Size())
|
||||
|
||||
var err error
|
||||
gpuCount, err = numGPUs()
|
||||
if err != nil || gpuCount <= 0 {
|
||||
gpuCount = 0
|
||||
}
|
||||
|
||||
// With exactly one GPU there is nothing to balance; getBestGPUDevice()
|
||||
// returns device 0 directly when loadBalancer is nil.
|
||||
// TODO: verify if 500 milliseconds is a good interval
|
||||
if gpuCount > 1 {
|
||||
loadBalancer = newGPULoadBalancer(500 * time.Millisecond)
|
||||
go loadBalancer.monitor()
|
||||
if gpuCount > 0 {
|
||||
snapshotStore = newGPUSnapshotStore()
|
||||
if gpuCount > 1 {
|
||||
loadBalancer = newGPULoadBalancer()
|
||||
go loadBalancer.monitor()
|
||||
}
|
||||
memoryPoolStore = newGPUMemoryPoolStore()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,225 +101,694 @@ func numGPUs() (int, error) {
|
||||
var rv C.int
|
||||
c := C.faiss_get_num_gpus(&rv)
|
||||
if c != 0 {
|
||||
return 0, fmt.Errorf("error getting number of GPUs, err: %v", getLastError())
|
||||
return 0, newFaissError(ErrGPUSetupFailed, getLastError(), int(c))
|
||||
}
|
||||
return int(rv), nil
|
||||
}
|
||||
|
||||
// gpuLoadBalancer monitors GPU free memory on a fixed interval, keeps a
|
||||
// memory-sorted list of devices, and hands them out in round-robin order.
|
||||
// At each interval the list is re-sorted and the round-robin counter resets
|
||||
// to 0, so the next cycle always starts from the GPU with the most free memory.
|
||||
type gpuLoadBalancer struct {
|
||||
mu sync.RWMutex
|
||||
sortedDevices []int
|
||||
idx atomic.Uint32
|
||||
interval time.Duration
|
||||
// scratch buffers reused across refresh calls; only accessed by the monitor goroutine
|
||||
freeMemory []uint64
|
||||
scratchDevs []int
|
||||
func getBestGPUDevice() (int, error) {
|
||||
if gpuCount == 0 {
|
||||
return 0, ErrNoUsableGPUDevices
|
||||
}
|
||||
if gpuCount == 1 {
|
||||
// if there's only one GPU, just return it
|
||||
// without going through the load balancer logic.
|
||||
return 0, nil
|
||||
}
|
||||
return loadBalancer.nextDevice(), nil
|
||||
}
|
||||
|
||||
func newGPULoadBalancer(interval time.Duration) *gpuLoadBalancer {
|
||||
func probeGPUDevice(device int) bool {
|
||||
var probeResult C.int
|
||||
c := C.faiss_probe_gpu(
|
||||
C.int(device),
|
||||
&probeResult,
|
||||
)
|
||||
return c == 0 && probeResult == 0
|
||||
}
|
||||
|
||||
// ---------------------------------
|
||||
// GPU Snapshot
|
||||
// ---------------------------------
|
||||
|
||||
// gpuSnapshot is a per-device view of GPU state.
|
||||
type gpuSnapshot struct {
|
||||
// GPU device id this snapshot describes.
|
||||
device int
|
||||
// Total memory in bytes in the GPU.
|
||||
totalMem uint64
|
||||
// Free memory in bytes in the GPU.
|
||||
freeMem atomic.Uint64
|
||||
}
|
||||
|
||||
// newGPUSnapshot creates a new gpuSnapshot for the given device.
|
||||
// assumed that the total memory available is also the initial free memory.
|
||||
func newGPUSnapshot(device int, totMemory uint64) *gpuSnapshot {
|
||||
s := &gpuSnapshot{device: device, totalMem: totMemory}
|
||||
s.setFreeMemory(totMemory)
|
||||
return s
|
||||
}
|
||||
|
||||
// reserve attempts to reserve the given size in bytes against the snapshot's free memory.
|
||||
// it ensures that atleast we remain under the data quota after the reservation, and returns
|
||||
// ErrGPUOutOfMemory if the reservation cannot be fulfilled.
|
||||
func (gs *gpuSnapshot) reserveMemory(required uint64) error {
|
||||
for {
|
||||
cur := gs.freeMemory()
|
||||
if required > cur {
|
||||
return ErrGPUOutOfMemory
|
||||
}
|
||||
after := cur - required
|
||||
if after < gs.poolQuota() {
|
||||
return ErrGPUOutOfMemory
|
||||
}
|
||||
if gs.freeMem.CompareAndSwap(cur, after) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// release adds the given size in bytes back to the snapshot's free memory.
|
||||
// it ensures that we never exceed the total memory of the GPU when releasing,
|
||||
// and caps the free memory at totalMem if that happens.
|
||||
func (gs *gpuSnapshot) releaseMemory(released uint64) {
|
||||
for {
|
||||
cur := gs.freeMemory()
|
||||
after := cur + released
|
||||
if after > gs.totalMem {
|
||||
after = gs.totalMem
|
||||
}
|
||||
if gs.freeMem.CompareAndSwap(cur, after) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (gs *gpuSnapshot) setFreeMemory(freeMem uint64) {
|
||||
gs.freeMem.Store(freeMem)
|
||||
}
|
||||
|
||||
func (gs *gpuSnapshot) freeMemory() uint64 {
|
||||
return gs.freeMem.Load()
|
||||
}
|
||||
|
||||
func (gs *gpuSnapshot) compare(other *gpuSnapshot) int {
|
||||
curFree := gs.freeMemory()
|
||||
otherFree := other.freeMemory()
|
||||
if curFree == otherFree {
|
||||
return 0
|
||||
} else if curFree < otherFree {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func (gs *gpuSnapshot) copyTo(other *gpuSnapshot) {
|
||||
other.device = gs.device
|
||||
other.totalMem = gs.totalMem
|
||||
other.setFreeMemory(gs.freeMemory())
|
||||
}
|
||||
|
||||
func (gs *gpuSnapshot) clone() *gpuSnapshot {
|
||||
clone := &gpuSnapshot{}
|
||||
gs.copyTo(clone)
|
||||
return clone
|
||||
}
|
||||
|
||||
func (gs *gpuSnapshot) poolQuota() uint64 {
|
||||
return uint64(float64(gs.totalMem) * defaultGPUPoolBudget)
|
||||
}
|
||||
|
||||
func (gs *gpuSnapshot) dataQuota() uint64 {
|
||||
return gs.totalMem - gs.poolQuota()
|
||||
}
|
||||
|
||||
// ---------------------------------
|
||||
// GPU Snapshot Store
|
||||
// ---------------------------------
|
||||
|
||||
// gpuSnapshotStore maintains a mapping of GPU device id to its snapshot,
|
||||
// providing thread-safe access and updates to GPU state information.
|
||||
type gpuSnapshotStore struct {
|
||||
// device -> snapshot immutable mapping
|
||||
// snapshot[i] always describes device i,
|
||||
// where i goes from 0 to gpuCount-1.
|
||||
snapshots []*gpuSnapshot
|
||||
}
|
||||
|
||||
func newGPUSnapshotStore() *gpuSnapshotStore {
|
||||
snapshots := make([]*gpuSnapshot, gpuCount)
|
||||
for device := 0; device < gpuCount; device++ {
|
||||
totMemory := uint64(0)
|
||||
// first probe if the device is healthy and can be used
|
||||
if probeGPUDevice(device) {
|
||||
var freeBytes C.size_t
|
||||
if c := C.faiss_gpu_free_memory(
|
||||
C.int(device),
|
||||
&freeBytes,
|
||||
); c == 0 {
|
||||
totMemory = uint64(freeBytes)
|
||||
}
|
||||
}
|
||||
// if we fail to get the free memory for the GPU,
|
||||
// we still create a snapshot with 0 total and free memory,
|
||||
// which will cause all reservation attempts to fail but won't cause any crashes.
|
||||
snapshots[device] = newGPUSnapshot(device, totMemory)
|
||||
}
|
||||
return &gpuSnapshotStore{snapshots: snapshots}
|
||||
}
|
||||
|
||||
func (gss *gpuSnapshotStore) snapshotForDevice(device int) *gpuSnapshot {
|
||||
return gss.snapshots[device]
|
||||
}
|
||||
|
||||
func (gss *gpuSnapshotStore) compare(i, j int) int {
|
||||
return gss.snapshots[i].compare(gss.snapshots[j])
|
||||
}
|
||||
|
||||
func (gss *gpuSnapshotStore) copyTo(other *gpuSnapshotStore) {
|
||||
for i := 0; i < gpuCount; i++ {
|
||||
gss.snapshots[i].copyTo(other.snapshots[i])
|
||||
}
|
||||
}
|
||||
|
||||
func (gss *gpuSnapshotStore) clone() *gpuSnapshotStore {
|
||||
clone := &gpuSnapshotStore{
|
||||
snapshots: make([]*gpuSnapshot, gpuCount),
|
||||
}
|
||||
for i := 0; i < gpuCount; i++ {
|
||||
clone.snapshots[i] = gss.snapshots[i].clone()
|
||||
}
|
||||
return clone
|
||||
}
|
||||
|
||||
// ---------------------------------
|
||||
// GPU Load Balancer
|
||||
// ---------------------------------
|
||||
|
||||
// gpuLoadBalancer distributes GPU allotments in a round-robin manner
|
||||
// in multi-GPU setups, while optimizing to always select the best GPU.
|
||||
type gpuLoadBalancer struct {
|
||||
cursor atomic.Uint32
|
||||
mu sync.RWMutex
|
||||
order []int
|
||||
scratchOrder []int
|
||||
scratchStore *gpuSnapshotStore
|
||||
}
|
||||
|
||||
func newGPULoadBalancer() *gpuLoadBalancer {
|
||||
lb := &gpuLoadBalancer{
|
||||
interval: interval,
|
||||
freeMemory: make([]uint64, gpuCount),
|
||||
scratchDevs: make([]int, 0, gpuCount),
|
||||
sortedDevices: make([]int, 0, gpuCount),
|
||||
order: make([]int, gpuCount),
|
||||
scratchOrder: make([]int, gpuCount),
|
||||
scratchStore: snapshotStore.clone(),
|
||||
}
|
||||
for i := 0; i < gpuCount; i++ {
|
||||
lb.order[i] = i
|
||||
lb.scratchOrder[i] = i
|
||||
}
|
||||
return lb
|
||||
}
|
||||
|
||||
// monitor periodically refreshes the GPU snapshots.
|
||||
func (lb *gpuLoadBalancer) monitor() {
|
||||
ticker := time.NewTicker(lb.interval)
|
||||
ticker := time.NewTicker(defaultGPULoadBalancerInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
// Perform an initial sort before any requests come in.
|
||||
lb.refresh()
|
||||
|
||||
for range ticker.C {
|
||||
lb.refresh()
|
||||
}
|
||||
}
|
||||
|
||||
// refresh queries every GPU for free memory, sorts the device list in descending
|
||||
// order of free memory, and resets the round-robin counter to 0.
|
||||
// If all queries fail the sorted list becomes empty, causing nextDevice to error.
|
||||
// refresh updates the load balancer's GPU snapshots by querying each GPU.
|
||||
func (lb *gpuLoadBalancer) refresh() {
|
||||
// Zero freeMemory before querying; failed queries leave their slot as 0,
|
||||
// which naturally excludes those devices from selection.
|
||||
clear(lb.freeMemory)
|
||||
lb.scratchDevs = lb.scratchDevs[:0]
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(gpuCount)
|
||||
for i := 0; i < gpuCount; i++ {
|
||||
go func(device int) {
|
||||
defer wg.Done()
|
||||
var freeBytes C.size_t
|
||||
if C.faiss_gpu_free_memory(C.int(device), &freeBytes) == 0 {
|
||||
lb.freeMemory[device] = uint64(freeBytes)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Only include devices that reported non-zero free memory, and have at least minGPUFreeMemory free.
|
||||
for i, mem := range lb.freeMemory {
|
||||
if mem > minGPUFreeMemory {
|
||||
lb.scratchDevs = append(lb.scratchDevs, i)
|
||||
}
|
||||
}
|
||||
|
||||
// Shuffle first, then sort descending by free memory to make the
|
||||
// sort as "unstable" as possible
|
||||
// This is useful to add fairness between GPUs with the same memory
|
||||
rand.Shuffle(len(lb.scratchDevs), func(i, j int) {
|
||||
lb.scratchDevs[i], lb.scratchDevs[j] = lb.scratchDevs[j], lb.scratchDevs[i]
|
||||
// refresh the scratch snapshots with the latest GPU state.
|
||||
snapshotStore.copyTo(lb.scratchStore)
|
||||
// Sort in descending order
|
||||
slices.SortFunc(lb.scratchOrder, func(i, j int) int {
|
||||
return lb.scratchStore.compare(j, i)
|
||||
})
|
||||
// Sort in a descending order by free memory so index 0 is the most appealing GPU.
|
||||
sort.Slice(lb.scratchDevs, func(i, j int) bool {
|
||||
return lb.freeMemory[lb.scratchDevs[i]] > lb.freeMemory[lb.scratchDevs[j]]
|
||||
})
|
||||
|
||||
// acquire lock to update the real order and reset the round-robin index,
|
||||
// ensuring that the next allocation cycle uses the updated order and
|
||||
// starts from the most appealing GPU.
|
||||
lb.mu.Lock()
|
||||
old := lb.sortedDevices
|
||||
lb.sortedDevices = lb.scratchDevs
|
||||
lb.scratchDevs = old[:0]
|
||||
lb.idx.Store(0)
|
||||
lb.mu.Unlock()
|
||||
defer lb.mu.Unlock()
|
||||
copy(lb.order, lb.scratchOrder)
|
||||
lb.cursor.Store(0)
|
||||
}
|
||||
|
||||
// nextDevice returns the next GPU device in round-robin order.
|
||||
// Returns an error if no devices are currently available.
|
||||
func (lb *gpuLoadBalancer) nextDevice() (int, error) {
|
||||
func (lb *gpuLoadBalancer) nextDevice() int {
|
||||
lb.mu.RLock()
|
||||
defer lb.mu.RUnlock()
|
||||
// atomically allocates the GPU.
|
||||
// Minus 1 for zero based index and modulo by gpuCount to wrap around.
|
||||
idx := (lb.cursor.Add(1) - 1) % uint32(gpuCount)
|
||||
// return the device id corresponding to the allocated GPU.
|
||||
return lb.order[idx]
|
||||
}
|
||||
|
||||
devices := lb.sortedDevices
|
||||
n := len(devices)
|
||||
if n == 0 {
|
||||
return 0, errAccessingGPUDevices
|
||||
// --------------------------------
|
||||
// GPU Index
|
||||
// --------------------------------
|
||||
|
||||
// GPUIndex is the interface for a Faiss index that resides on GPU.
|
||||
type GPUIndex interface {
|
||||
// D returns the dimension of the indexed vectors.
|
||||
D() int
|
||||
// Add adds vectors to the index.
|
||||
Add(x []float32) error
|
||||
// Train trains the index on a representative set of vectors.
|
||||
Train(x []float32) error
|
||||
// Search queries the index with the vectors in x.
|
||||
// Returns the IDs of the k nearest neighbors for each query vector and the
|
||||
// corresponding distances.
|
||||
Search(x []float32, k int64) (distances []float32, labels []int64, err error)
|
||||
// Size estimates the memory footprint of the index assuming in bytes,
|
||||
// if the underlying faiss index is memory-mapped and not fully loaded into memory.
|
||||
Size() uint64
|
||||
// Close frees the memory used by the index.
|
||||
Close()
|
||||
// gPtr returns the underlying C pointer to the FaissGpuIndex.
|
||||
gPtr() *C.FaissGpuIndex
|
||||
}
|
||||
|
||||
// faissGPUIndex concrete implementation of GPUIndex.
|
||||
type faissGPUIndex struct {
|
||||
idx *C.FaissGpuIndex
|
||||
ctx *gpuContext
|
||||
}
|
||||
|
||||
func (g *faissGPUIndex) D() int {
|
||||
return int(C.faiss_GpuIndex_d(g.idx))
|
||||
}
|
||||
|
||||
func (g *faissGPUIndex) Add(x []float32) error {
|
||||
n := len(x) / g.D()
|
||||
reservedMem, err := g.prepareAdd(n, x)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// atomically allocates the GPU. Minus 1 for zero based index
|
||||
idx := lb.idx.Add(1) - 1
|
||||
return devices[int(idx%uint32(n))], nil
|
||||
}
|
||||
|
||||
func getBestGPUDevice() (int, error) {
|
||||
if gpuCount == 0 {
|
||||
return 0, errNoGPUDevices
|
||||
if c := C.faiss_GpuIndex_add(
|
||||
g.idx,
|
||||
C.idx_t(n),
|
||||
(*C.float)(&x[0]),
|
||||
); c != 0 {
|
||||
g.ctx.releaseMemory(reservedMem)
|
||||
return newFaissError(ErrAddFailed, getLastError(), int(c))
|
||||
}
|
||||
// With exactly one GPU there is nothing to balance; always use device 0.
|
||||
if loadBalancer == nil {
|
||||
return 0, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *faissGPUIndex) Train(x []float32) error {
|
||||
n := len(x) / g.D()
|
||||
if c := C.faiss_GpuIndex_train(
|
||||
g.idx,
|
||||
C.idx_t(n),
|
||||
(*C.float)(&x[0]),
|
||||
); c != 0 {
|
||||
return newFaissError(ErrTrainFailed, getLastError(), int(c))
|
||||
}
|
||||
return loadBalancer.nextDevice()
|
||||
return nil
|
||||
}
|
||||
|
||||
// only expose API used by zapx
|
||||
type GPUIndexImpl struct {
|
||||
idx *faissIndex
|
||||
gpuResource *C.FaissStandardGpuResources
|
||||
func (g *faissGPUIndex) Search(x []float32, k int64) (
|
||||
[]float32, []int64, error) {
|
||||
n := len(x) / g.D()
|
||||
distances := make([]float32, int64(n)*k)
|
||||
labels := make([]int64, int64(n)*k)
|
||||
if c := C.faiss_GpuIndex_search(
|
||||
g.idx,
|
||||
C.idx_t(n),
|
||||
(*C.float)(&x[0]),
|
||||
C.idx_t(k),
|
||||
(*C.float)(&distances[0]),
|
||||
(*C.idx_t)(&labels[0]),
|
||||
); c != 0 {
|
||||
return nil, nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
return distances, labels, nil
|
||||
}
|
||||
|
||||
func (g *GPUIndexImpl) cPtr() *C.FaissIndex {
|
||||
return g.idx.idx
|
||||
}
|
||||
|
||||
func (g *GPUIndexImpl) Train(x []float32) error {
|
||||
return g.idx.Train(x)
|
||||
}
|
||||
|
||||
func (g *GPUIndexImpl) Add(x []float32) error {
|
||||
return g.idx.Add(x)
|
||||
}
|
||||
|
||||
func (g *GPUIndexImpl) Search(x []float32, k int64) ([]float32, []int64, error) {
|
||||
return g.idx.Search(x, k)
|
||||
}
|
||||
|
||||
func (g *GPUIndexImpl) Close() {
|
||||
func (g *faissGPUIndex) Close() {
|
||||
if g.idx != nil {
|
||||
g.idx.Close()
|
||||
C.faiss_GpuIndex_free(g.idx)
|
||||
g.idx = nil
|
||||
}
|
||||
if g.gpuResource != nil {
|
||||
C.faiss_StandardGpuResources_free(g.gpuResource)
|
||||
g.gpuResource = nil
|
||||
if g.ctx != nil {
|
||||
g.ctx.delete()
|
||||
g.ctx = nil
|
||||
}
|
||||
}
|
||||
|
||||
// CloneToGPU transfers a CPU index to the best available GPU based on free memory.
|
||||
func (g *faissGPUIndex) Size() uint64 {
|
||||
return reflectStaticSizeFaissGPUIndex
|
||||
}
|
||||
|
||||
func (g *faissGPUIndex) gPtr() *C.FaissGpuIndex {
|
||||
return g.idx
|
||||
}
|
||||
|
||||
// prepareAdd performs the necessary steps to prepare the GPU index for adding new vectors,
|
||||
// including calculating the required memory for the new vectors based on their assignments
|
||||
// and reserving that memory in the GPU snapshot.
|
||||
// It returns the amount of memory reserved if no error occurs, or an error if the reservation fails.
|
||||
func (g *faissGPUIndex) prepareAdd(n int, x []float32) (uint64, error) {
|
||||
// fallback estimate of required memory based on code size,
|
||||
// used for non-IVF indexes or if assignment fails.
|
||||
requiredMem := uint64(n) * g.ctx.codeSize
|
||||
// For IVF Indexes, we follow the following algorithm to
|
||||
// calculate the required memory for the new vectors to be added:
|
||||
// 1. Get the list assignment for each vector to be added.
|
||||
// 2. Count the number of vectors assigned to each list.
|
||||
// 3. Calculate the required memory for the new vectors based on their assignments.
|
||||
// 4. Reserve the required memory in the GPU snapshot.
|
||||
// 5. Actually reserve the memory on the GPU for the new vectors based on their assignments.
|
||||
ivfIdx := C.faiss_GpuIndexIVF_cast(g.idx)
|
||||
if ivfIdx != nil {
|
||||
// 1. list assignment for each vector.
|
||||
assign := make([]int64, n)
|
||||
if c := C.faiss_GpuIndexIVF_assign(
|
||||
ivfIdx,
|
||||
C.idx_t(n),
|
||||
(*C.float)(&x[0]),
|
||||
(*C.idx_t)(&assign[0]),
|
||||
); c != 0 {
|
||||
if err := g.ctx.reserveMemory(requiredMem); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return requiredMem, nil
|
||||
}
|
||||
// 2. find the list count for the assigned vectors.
|
||||
nlist := uint64(C.faiss_GpuIndexIVF_nlist(ivfIdx))
|
||||
listCount := make([]int64, nlist)
|
||||
for _, a := range assign {
|
||||
if a >= 0 && a < int64(nlist) {
|
||||
listCount[a]++
|
||||
}
|
||||
}
|
||||
// 3. compute required memory for the new vectors based on their assignments.
|
||||
var size C.size_t
|
||||
if c := C.faiss_GpuIndexIVF_compute_required_memory(
|
||||
ivfIdx,
|
||||
C.size_t(nlist),
|
||||
(*C.idx_t)(&listCount[0]),
|
||||
&size,
|
||||
); c != 0 {
|
||||
if err := g.ctx.reserveMemory(requiredMem); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return requiredMem, nil
|
||||
}
|
||||
// 4. reserve on our snapshot.
|
||||
requiredMem = uint64(size)
|
||||
if err := g.ctx.reserveMemory(requiredMem); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// 5. reserve on GPU.
|
||||
if c := C.faiss_GpuIndexIVF_reserve_assigned_memory(
|
||||
ivfIdx,
|
||||
C.size_t(nlist),
|
||||
(*C.idx_t)(&listCount[0]),
|
||||
); c != 0 {
|
||||
g.ctx.releaseMemory(requiredMem)
|
||||
return 0, newFaissError(ErrGPUOutOfMemory, getLastError(), int(c))
|
||||
}
|
||||
return requiredMem, nil
|
||||
}
|
||||
if err := g.ctx.reserveMemory(requiredMem); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return requiredMem, nil
|
||||
}
|
||||
|
||||
type GPUIndexImpl struct {
|
||||
GPUIndex
|
||||
}
|
||||
|
||||
// CloneToGPU clones cpuIndex onto a GPU and returns the resulting index.
|
||||
func CloneToGPU(cpuIndex *IndexImpl) (*GPUIndexImpl, error) {
|
||||
if cpuIndex == nil {
|
||||
return nil, errNilIndex
|
||||
return nil, ErrIndexNil
|
||||
}
|
||||
|
||||
// Use the load balancer to select the best GPU device
|
||||
// Use the load balancer to select the best GPU device's current snapshot.
|
||||
device, err := getBestGPUDevice()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var gpuResource *C.FaissStandardGpuResources
|
||||
if code := C.faiss_StandardGpuResources_new(&gpuResource); code != 0 {
|
||||
return nil, fmt.Errorf("failed to initialize GPU resources: error code %d, err: %v", code, getLastError())
|
||||
// Get the code size of the index to set up the context
|
||||
codeSize, err := cpuIndex.CodeSize()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Disable the pre-allocated temp memory pool so that all GPU memory is
|
||||
// available for index data; unified memory mode handles intermediate
|
||||
// allocations via cudaMalloc/cudaFree on demand.
|
||||
if code := C.faiss_StandardGpuResources_noTempMemory(gpuResource); code != 0 {
|
||||
C.faiss_StandardGpuResources_free(gpuResource)
|
||||
return nil, fmt.Errorf("failed to disable GPU temp memory: error code %d, err: %v", code, getLastError())
|
||||
// Create the GPU context with the selected device.
|
||||
ctx, err := newGPUContext(device, codeSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var clonerOpts *C.FaissGpuClonerOptions
|
||||
if code := C.faiss_GpuClonerOptions_new(&clonerOpts); code != 0 {
|
||||
C.faiss_StandardGpuResources_free(gpuResource)
|
||||
return nil, fmt.Errorf("failed to create cloner options: error code %d, err: %v", code, getLastError())
|
||||
// Estimate the GPU memory the clone will need and reserve it against
|
||||
// the GPU snapshot before paying the cost of the actual clone. The
|
||||
// estimator uses the same cloner options we will pass to the clone
|
||||
// call, so the interleaved-layout / indices-options / coarse-quantizer
|
||||
// width all match what faiss will allocate.
|
||||
requiredMem := ctx.estimateRequiredMemory(cpuIndex)
|
||||
if err := ctx.reserveMemory(requiredMem); err != nil {
|
||||
ctx.delete()
|
||||
return nil, err
|
||||
}
|
||||
defer C.faiss_GpuClonerOptions_free(clonerOpts)
|
||||
|
||||
C.faiss_GpuClonerOptions_set_memorySpace(clonerOpts, C.int(defaultGPUMemoryMode))
|
||||
|
||||
// Clone the index to GPU
|
||||
var gpuIdx *C.FaissGpuIndex
|
||||
code := C.faiss_index_cpu_to_gpu_with_options(
|
||||
gpuResource,
|
||||
if c := C.faiss_index_cpu_to_gpu_with_options(
|
||||
ctx.resource.cPtr(),
|
||||
C.int(device),
|
||||
cpuIndex.cPtr(),
|
||||
clonerOpts,
|
||||
ctx.options.cPtr(),
|
||||
&gpuIdx,
|
||||
)
|
||||
if code != 0 {
|
||||
C.faiss_StandardGpuResources_free(gpuResource)
|
||||
return nil, fmt.Errorf("failed to transfer index to GPU device %d: error code %d, err: %v", device, code, getLastError())
|
||||
); c != 0 {
|
||||
ctx.delete()
|
||||
return nil, newFaissError(ErrGPUCloneFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
idx := &faissIndex{
|
||||
idx: (*C.FaissIndex)(unsafe.Pointer(gpuIdx)),
|
||||
idx := &faissGPUIndex{
|
||||
idx: gpuIdx,
|
||||
ctx: ctx,
|
||||
}
|
||||
|
||||
return &GPUIndexImpl{
|
||||
idx: idx,
|
||||
gpuResource: gpuResource,
|
||||
}, nil
|
||||
return &GPUIndexImpl{idx}, nil
|
||||
}
|
||||
|
||||
func CloneToCPU(gpuIndex *GPUIndexImpl) (*IndexImpl, error) {
|
||||
if gpuIndex == nil {
|
||||
return nil, errNilIndex
|
||||
return nil, ErrIndexNil
|
||||
}
|
||||
|
||||
var cpuIdx *C.FaissIndex
|
||||
code := C.faiss_index_gpu_to_cpu(
|
||||
gpuIndex.cPtr(),
|
||||
if c := C.faiss_index_gpu_to_cpu(
|
||||
gpuIndex.gPtr(),
|
||||
&cpuIdx,
|
||||
)
|
||||
if code != 0 {
|
||||
return nil, fmt.Errorf("failed to transfer index to CPU: %v", getLastError())
|
||||
); c != 0 {
|
||||
return nil, newFaissError(ErrGPUCloneFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IndexImpl{&faissIndex{idx: cpuIdx}}, nil
|
||||
}
|
||||
|
||||
// --------------------------------
|
||||
// GPU Context
|
||||
// --------------------------------
|
||||
|
||||
// gpuContext provides the context for the GPU clone operation.
|
||||
type gpuContext struct {
|
||||
resource *gpuResource
|
||||
options *gpuClonerOptions
|
||||
device int
|
||||
codeSize uint64
|
||||
memReserved uint64
|
||||
}
|
||||
|
||||
func newGPUContext(device int, codeSize uint64) (*gpuContext, error) {
|
||||
res, err := newGPUResource(device)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clonerOpts, err := newGPUClonerOptions()
|
||||
if err != nil {
|
||||
res.delete()
|
||||
return nil, err
|
||||
}
|
||||
return &gpuContext{
|
||||
resource: res,
|
||||
options: clonerOpts,
|
||||
device: device,
|
||||
codeSize: codeSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *gpuContext) delete() {
|
||||
if c.options != nil {
|
||||
c.options.delete()
|
||||
c.options = nil
|
||||
}
|
||||
if c.resource != nil {
|
||||
c.resource.delete()
|
||||
c.resource = nil
|
||||
}
|
||||
if c.memReserved > 0 {
|
||||
c.releaseMemory(c.memReserved)
|
||||
c.memReserved = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (c *gpuContext) reserveMemory(size uint64) error {
|
||||
snapshot := snapshotStore.snapshotForDevice(c.device)
|
||||
if err := snapshot.reserveMemory(size); err != nil {
|
||||
return err
|
||||
}
|
||||
c.memReserved += size
|
||||
return nil
|
||||
}
|
||||
|
||||
// estimateRequiredMemory predicts the GPU memory the clone of cpuIndex
|
||||
// will consume on this context's device, given the cloner options. It
|
||||
// accounts for the interleaved storage layout that faiss uses on the GPU.
|
||||
// Falls back to a code_size * ntotal estimate if the C API does not
|
||||
// recognize the index type. Always accounts for the cloned index's temporary memory.
|
||||
func (c *gpuContext) estimateRequiredMemory(cpuIndex *IndexImpl) uint64 {
|
||||
rv := uint64(defaultGPUTempMemorySize)
|
||||
numVecs := uint64(cpuIndex.Ntotal())
|
||||
if numVecs > 0 {
|
||||
var size C.size_t
|
||||
if rc := C.faiss_GpuMemoryEstimate_for_cpu_index(
|
||||
cpuIndex.cPtr(),
|
||||
C.int(c.device),
|
||||
c.options.cPtr(),
|
||||
&size,
|
||||
); rc != 0 {
|
||||
rv += numVecs * c.codeSize
|
||||
} else {
|
||||
rv += uint64(size)
|
||||
}
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
func (c *gpuContext) releaseMemory(size uint64) {
|
||||
snapshot := snapshotStore.snapshotForDevice(c.device)
|
||||
snapshot.releaseMemory(size)
|
||||
c.memReserved -= size
|
||||
}
|
||||
|
||||
// gpuResource wraps a FAISS standard GPU resources handle.
|
||||
type gpuResource struct {
|
||||
res *C.FaissStandardGpuResources
|
||||
}
|
||||
|
||||
// newGPUResource creates a new GPU resource handle for the given device,
|
||||
// configuring it with the shared memory overflow pool, per-index temporary
|
||||
// buffers, and pinned memory for CPU-GPU transfers.
|
||||
func newGPUResource(device int) (*gpuResource, error) {
|
||||
var res *C.FaissStandardGpuResources
|
||||
if c := C.faiss_StandardGpuResources_new(&res); c != 0 {
|
||||
return nil, newFaissError(ErrGPUContextFailed, getLastError(), int(c))
|
||||
}
|
||||
pool := memoryPoolStore.poolForDevice(device)
|
||||
if pool != nil {
|
||||
if c := C.faiss_StandardGpuResources_setTempMemoryOverflowPool(res, pool.cPtr()); c != 0 {
|
||||
C.faiss_StandardGpuResources_free(res)
|
||||
return nil, newFaissError(ErrGPUContextFailed, getLastError(), int(c))
|
||||
}
|
||||
}
|
||||
if c := C.faiss_StandardGpuResources_setTempMemory(res, C.size_t(defaultGPUTempMemorySize)); c != 0 {
|
||||
C.faiss_StandardGpuResources_free(res)
|
||||
return nil, newFaissError(ErrGPUContextFailed, getLastError(), int(c))
|
||||
}
|
||||
if c := C.faiss_StandardGpuResources_setPinnedMemory(res, C.size_t(defaultGPUPinnedMemory)); c != 0 {
|
||||
C.faiss_StandardGpuResources_free(res)
|
||||
return nil, newFaissError(ErrGPUContextFailed, getLastError(), int(c))
|
||||
}
|
||||
return &gpuResource{res: res}, nil
|
||||
}
|
||||
|
||||
func (r *gpuResource) cPtr() *C.FaissStandardGpuResources {
|
||||
return r.res
|
||||
}
|
||||
|
||||
func (r *gpuResource) delete() {
|
||||
if r.res != nil {
|
||||
C.faiss_StandardGpuResources_free(r.res)
|
||||
r.res = nil
|
||||
}
|
||||
}
|
||||
|
||||
// gpuClonerOptions wraps a FAISS GPU cloner options handle.
|
||||
type gpuClonerOptions struct {
|
||||
opts *C.FaissGpuClonerOptions
|
||||
}
|
||||
|
||||
func newGPUClonerOptions() (*gpuClonerOptions, error) {
|
||||
var opts *C.FaissGpuClonerOptions
|
||||
if c := C.faiss_GpuClonerOptions_new(&opts); c != 0 {
|
||||
return nil, newFaissError(ErrGPUContextFailed, getLastError(), int(c))
|
||||
}
|
||||
C.faiss_GpuClonerOptions_set_memorySpace(opts, C.int(defaultGPUMemoryMode))
|
||||
return &gpuClonerOptions{opts: opts}, nil
|
||||
}
|
||||
|
||||
func (c *gpuClonerOptions) cPtr() *C.FaissGpuClonerOptions {
|
||||
return c.opts
|
||||
}
|
||||
|
||||
func (c *gpuClonerOptions) delete() {
|
||||
if c.opts != nil {
|
||||
C.faiss_GpuClonerOptions_free(c.opts)
|
||||
c.opts = nil
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------
|
||||
// GPU Memory Pool Store
|
||||
// --------------------------------
|
||||
|
||||
// gpuMemoryPoolStore indicates a per-device reusable pool of GPU memory
|
||||
// that grows dynamically up to a threshold.
|
||||
type gpuMemoryPoolStore struct {
|
||||
devicePool []*gpuMemoryPool
|
||||
}
|
||||
|
||||
func newGPUMemoryPoolStore() *gpuMemoryPoolStore {
|
||||
pool := make([]*gpuMemoryPool, gpuCount)
|
||||
for i := 0; i < gpuCount; i++ {
|
||||
device := snapshotStore.snapshotForDevice(i)
|
||||
pq := device.poolQuota()
|
||||
if pq > 0 {
|
||||
pool[i] = newGPUMemoryPool(i, pq)
|
||||
}
|
||||
}
|
||||
return &gpuMemoryPoolStore{devicePool: pool}
|
||||
}
|
||||
|
||||
func (mps *gpuMemoryPoolStore) poolForDevice(device int) *gpuMemoryPool {
|
||||
return mps.devicePool[device]
|
||||
}
|
||||
|
||||
// gpuMemoryPool wraps a FAISS GPU memory pool handle.
|
||||
type gpuMemoryPool struct {
|
||||
pool *C.FaissGpuMemoryPool
|
||||
}
|
||||
|
||||
func newGPUMemoryPool(device int, cap uint64) *gpuMemoryPool {
|
||||
var pool *C.FaissGpuMemoryPool
|
||||
if c := C.faiss_GpuMemoryPool_new(
|
||||
C.int(device),
|
||||
C.size_t(cap),
|
||||
&pool,
|
||||
); c == 0 {
|
||||
return &gpuMemoryPool{pool: pool}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mp *gpuMemoryPool) cPtr() *C.FaissGpuMemoryPool {
|
||||
return mp.pool
|
||||
}
|
||||
|
||||
func (mp *gpuMemoryPool) delete() {
|
||||
if mp.pool != nil {
|
||||
C.faiss_GpuMemoryPool_free(mp.pool)
|
||||
mp.pool = nil
|
||||
}
|
||||
}
|
||||
+8
-10
@@ -13,29 +13,27 @@
|
||||
// limitations under the License.
|
||||
|
||||
//go:build !gpu
|
||||
// +build !gpu
|
||||
|
||||
package faiss
|
||||
|
||||
import "errors"
|
||||
|
||||
// GPUIndexImpl is an opaque type when not built with GPU support.
|
||||
type GPUIndexImpl struct{}
|
||||
|
||||
func (g *GPUIndexImpl) Train(x []float32) error { return errGPUNotBuilt }
|
||||
func (g *GPUIndexImpl) Add(x []float32) error { return errGPUNotBuilt }
|
||||
func (g *GPUIndexImpl) Train(x []float32) error { return ErrNoUsableGPUDevices }
|
||||
func (g *GPUIndexImpl) Add(x []float32) error { return ErrNoUsableGPUDevices }
|
||||
func (g *GPUIndexImpl) Search(x []float32, k int64) ([]float32, []int64, error) {
|
||||
return nil, nil, errGPUNotBuilt
|
||||
return nil, nil, ErrNoUsableGPUDevices
|
||||
}
|
||||
func (g *GPUIndexImpl) Close() {}
|
||||
|
||||
var errGPUNotBuilt = errors.New("not built with GPU support (requires -tags gpu)")
|
||||
func (g *GPUIndexImpl) Close() {}
|
||||
func (g *GPUIndexImpl) Size() uint64 { return 0 }
|
||||
|
||||
// CloneToGPU is not available without the gpu build tag.
|
||||
func CloneToGPU(_ *IndexImpl) (*GPUIndexImpl, error) {
|
||||
return nil, errGPUNotBuilt
|
||||
return nil, ErrNoUsableGPUDevices
|
||||
}
|
||||
|
||||
// CloneToCPU is not available without the gpu build tag.
|
||||
func CloneToCPU(_ *GPUIndexImpl) (*IndexImpl, error) {
|
||||
return nil, errGPUNotBuilt
|
||||
return nil, ErrNoUsableGPUDevices
|
||||
}
|
||||
+51
-27
@@ -13,11 +13,18 @@ package faiss
|
||||
import "C"
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var reflectStaticSizeFaissIndex uint64
|
||||
|
||||
func init() {
|
||||
var f faissIndex
|
||||
reflectStaticSizeFaissIndex = uint64(reflect.TypeOf(f).Size())
|
||||
}
|
||||
|
||||
// Index is a Faiss index.
|
||||
//
|
||||
// Note that some index implementations do not support all methods.
|
||||
@@ -120,14 +127,19 @@ type Index interface {
|
||||
// Close frees the memory used by the index.
|
||||
Close()
|
||||
|
||||
// consults the C++ side to get the size of the index
|
||||
// Size estimates the memory footprint of the index in bytes,
|
||||
// if the underlying faiss index is memory-mapped and not fully loaded into memory.
|
||||
Size() uint64
|
||||
|
||||
// cPtr returns a pointer to the underlying C index struct.
|
||||
cPtr() *C.FaissIndex
|
||||
|
||||
// set the quantizers from a source index into this index, applicable only
|
||||
// for IVF indexes
|
||||
SetQuantizers(source Index) error
|
||||
|
||||
// CodeSize returns the size of the produced codes in bytes.
|
||||
CodeSize() (uint64, error)
|
||||
}
|
||||
|
||||
type faissIndex struct {
|
||||
@@ -139,14 +151,26 @@ func (idx *faissIndex) cPtr() *C.FaissIndex {
|
||||
}
|
||||
|
||||
func (idx *faissIndex) Size() uint64 {
|
||||
size := C.faiss_Index_size(idx.idx)
|
||||
return uint64(size)
|
||||
rv := reflectStaticSizeFaissIndex
|
||||
var size C.size_t
|
||||
if code := C.faiss_Index_size(idx.idx, &size); code == 0 {
|
||||
rv += uint64(size)
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
func (idx *faissIndex) D() int {
|
||||
return int(C.faiss_Index_d(idx.idx))
|
||||
}
|
||||
|
||||
func (idx *faissIndex) CodeSize() (uint64, error) {
|
||||
var size C.size_t
|
||||
if c := C.faiss_Index_sa_code_size(idx.idx, &size); c != 0 {
|
||||
return 0, newFaissError(ErrInspectIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return uint64(size), nil
|
||||
}
|
||||
|
||||
func (idx *faissIndex) IsTrained() bool {
|
||||
return C.faiss_Index_is_trained(idx.idx) != 0
|
||||
}
|
||||
@@ -162,7 +186,7 @@ func (idx *faissIndex) MetricType() int {
|
||||
func (idx *faissIndex) Train(x []float32) error {
|
||||
n := len(x) / idx.D()
|
||||
if c := C.faiss_Index_train(idx.idx, C.idx_t(n), (*C.float)(&x[0])); c != 0 {
|
||||
return getLastError()
|
||||
return newFaissError(ErrTrainFailed, getLastError(), int(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -170,7 +194,7 @@ func (idx *faissIndex) Train(x []float32) error {
|
||||
func (idx *faissIndex) Add(x []float32) error {
|
||||
n := len(x) / idx.D()
|
||||
if c := C.faiss_Index_add(idx.idx, C.idx_t(n), (*C.float)(&x[0])); c != 0 {
|
||||
return getLastError()
|
||||
return newFaissError(ErrAddFailed, getLastError(), int(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -179,7 +203,7 @@ func (idx *faissIndex) ObtainClusterVectorCountsFromIVFIndex(includedVectors Sel
|
||||
// Applicable only to IVF indexes
|
||||
ivfPtr := C.faiss_IndexIVF_cast(idx.cPtr())
|
||||
if ivfPtr == nil {
|
||||
return nil, errNotIVFIndex
|
||||
return nil, ErrNotIVFIndex
|
||||
}
|
||||
// Creating a slice to hold the count of vectors per cluster
|
||||
// Since we have nlist clusters, we create a slice of size nlist
|
||||
@@ -200,7 +224,7 @@ func (idx *faissIndex) ObtainClusterVectorCountsFromIVFIndex(includedVectors Sel
|
||||
C.size_t(nlist),
|
||||
params.sp,
|
||||
); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrInspectIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return listCount, nil
|
||||
}
|
||||
@@ -221,7 +245,7 @@ func (idx *faissIndex) ObtainClustersWithDistancesFromIVFIndex(x []float32, incl
|
||||
// Applicable only to IVF indexes
|
||||
ivfPtr := C.faiss_IndexIVF_cast(idx.cPtr())
|
||||
if ivfPtr == nil {
|
||||
return nil, nil, errNotIVFIndex
|
||||
return nil, nil, ErrNotIVFIndex
|
||||
}
|
||||
params, err := NewStandardSearchParams(includedCentroids)
|
||||
if err != nil {
|
||||
@@ -244,7 +268,7 @@ func (idx *faissIndex) ObtainClustersWithDistancesFromIVFIndex(x []float32, incl
|
||||
(*C.idx_t)(¢roids[0]),
|
||||
params.sp,
|
||||
); c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return centroids, centroidDistances, nil
|
||||
@@ -275,7 +299,7 @@ func (idx *faissIndex) ObtainKCentroidCardinalitiesFromIVFIndex(limit int, desce
|
||||
nil,
|
||||
)
|
||||
if c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrInspectIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
topIndices := getIndicesOfKCentroidCardinalities(
|
||||
@@ -328,12 +352,12 @@ func (idx *faissIndex) SearchClustersFromIVFIndex(eligibleCentroidIDs []int64, c
|
||||
// Applicable only to IVF indexes
|
||||
ivfPtr := C.faiss_IndexIVF_cast(idx.cPtr())
|
||||
if ivfPtr == nil {
|
||||
return nil, nil, errNotIVFIndex
|
||||
return nil, nil, ErrNotIVFIndex
|
||||
}
|
||||
// If no include selector is provided, we have no results to return.
|
||||
// return an error indicating that the SearchClustersFromIVFIndex requires a valid selector.
|
||||
if include == nil {
|
||||
return nil, nil, fmt.Errorf("SearchClustersFromIVFIndex requires a valid include selector")
|
||||
return nil, nil, ErrSelectorNil
|
||||
}
|
||||
// create a temporary search params object to set nprobe, this will override
|
||||
// the nprobe and the nlist set at index time, this will allow the search to
|
||||
@@ -377,7 +401,7 @@ func (idx *faissIndex) SearchClustersFromIVFIndex(eligibleCentroidIDs []int64, c
|
||||
(C.int)(0),
|
||||
searchParams.sp,
|
||||
); c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return distances, labels, nil
|
||||
@@ -391,7 +415,7 @@ func (idx *faissIndex) AddWithIDs(x []float32, xids []int64) error {
|
||||
(*C.float)(&x[0]),
|
||||
(*C.idx_t)(&xids[0]),
|
||||
); c != 0 {
|
||||
return getLastError()
|
||||
return newFaissError(ErrAddFailed, getLastError(), int(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -413,7 +437,7 @@ func (idx *faissIndex) Search(x []float32, k int64) (
|
||||
(*C.float)(&distances[0]),
|
||||
(*C.idx_t)(&labels[0]),
|
||||
); c != 0 {
|
||||
err = getLastError()
|
||||
err = newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return
|
||||
@@ -433,7 +457,7 @@ func (idx *faissIndex) Reconstruct(key int64) (recons []float32, err error) {
|
||||
C.idx_t(key),
|
||||
(*C.float)(&rv[0]),
|
||||
); c != 0 {
|
||||
err = getLastError()
|
||||
err = newFaissError(ErrReconstructFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return rv, err
|
||||
@@ -448,7 +472,7 @@ func (idx *faissIndex) ReconstructBatch(keys []int64, recons []float32) ([]float
|
||||
(*C.idx_t)(&keys[0]),
|
||||
(*C.float)(&recons[0]),
|
||||
); c != 0 {
|
||||
err = getLastError()
|
||||
err = newFaissError(ErrReconstructFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return recons, err
|
||||
@@ -459,7 +483,7 @@ func (idx *faissIndex) MergeFrom(other Index, add_id int64) (err error) {
|
||||
// todo: support on Flat index as well
|
||||
if !(idx.IsIVFIndex() && other.IsIVFIndex()) &&
|
||||
!(idx.IsSQIndex() && other.IsSQIndex()) {
|
||||
return fmt.Errorf("faissIndex MergeFrom err: %w", errMergeFromNotSupported)
|
||||
return ErrMergeFromNotSupported
|
||||
}
|
||||
|
||||
if c := C.faiss_Index_merge_from(
|
||||
@@ -467,7 +491,7 @@ func (idx *faissIndex) MergeFrom(other Index, add_id int64) (err error) {
|
||||
other.cPtr(),
|
||||
(C.idx_t)(add_id),
|
||||
); c != 0 {
|
||||
err = getLastError()
|
||||
err = newFaissError(ErrMergeFromFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return err
|
||||
@@ -479,7 +503,7 @@ func (idx *faissIndex) RangeSearch(x []float32, radius float32) (
|
||||
n := len(x) / idx.D()
|
||||
var rsr *C.FaissRangeSearchResult
|
||||
if c := C.faiss_RangeSearchResult_new(&rsr, C.idx_t(n)); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
if c := C.faiss_Index_range_search(
|
||||
idx.idx,
|
||||
@@ -488,7 +512,7 @@ func (idx *faissIndex) RangeSearch(x []float32, radius float32) (
|
||||
C.float(radius),
|
||||
rsr,
|
||||
); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
return &RangeSearchResult{rsr}, nil
|
||||
}
|
||||
@@ -497,7 +521,7 @@ func (idx *faissIndex) DistCompute(queryData []float32, ids []int64) ([]float32,
|
||||
distances := make([]float32, len(ids))
|
||||
if c := C.faiss_Index_dist_compute(idx.idx, (*C.float)(&queryData[0]),
|
||||
(*C.idx_t)(&ids[0]), (C.size_t)(len(ids)), (*C.float)(&distances[0])); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return distances, nil
|
||||
@@ -505,7 +529,7 @@ func (idx *faissIndex) DistCompute(queryData []float32, ids []int64) ([]float32,
|
||||
|
||||
func (idx *faissIndex) Reset() error {
|
||||
if c := C.faiss_Index_reset(idx.idx); c != 0 {
|
||||
return getLastError()
|
||||
return newFaissError(ErrResetIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -513,7 +537,7 @@ func (idx *faissIndex) Reset() error {
|
||||
func (idx *faissIndex) RemoveIDs(sel *IDSelector) (int, error) {
|
||||
var nRemoved C.size_t
|
||||
if c := C.faiss_Index_remove_ids(idx.idx, sel.sel, &nRemoved); c != 0 {
|
||||
return 0, getLastError()
|
||||
return 0, newFaissError(ErrRemoveIDsFailed, getLastError(), int(c))
|
||||
}
|
||||
return int(nRemoved), nil
|
||||
}
|
||||
@@ -543,7 +567,7 @@ func (idx *faissIndex) searchWithOptions(x []float32, k int64, sel Selector, par
|
||||
(*C.float)(&distances[0]),
|
||||
(*C.idx_t)(&labels[0]),
|
||||
); c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
return distances, labels, nil
|
||||
}
|
||||
@@ -600,7 +624,7 @@ func IndexFactory(d int, description string, metric int) (*IndexImpl, error) {
|
||||
var idx faissIndex
|
||||
c := C.faiss_index_factory(&idx.idx, C.int(d), cdesc, C.FaissMetricType(metric))
|
||||
if c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IndexImpl{&idx}, nil
|
||||
}
|
||||
|
||||
+52
-39
@@ -12,10 +12,17 @@ package faiss
|
||||
import "C"
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var reflectStaticSizeFaissBinaryIndex uint64
|
||||
|
||||
func init() {
|
||||
var b faissBinaryIndex
|
||||
reflectStaticSizeFaissBinaryIndex = uint64(reflect.TypeOf(b).Size())
|
||||
}
|
||||
|
||||
type BinaryIndex interface {
|
||||
// D returns the dimension of the indexed vectors.
|
||||
D() int
|
||||
@@ -88,13 +95,18 @@ type BinaryIndex interface {
|
||||
centroidsToProbe int, xb []uint8, k int64, include Selector,
|
||||
params json.RawMessage) ([]int32, []int64, error)
|
||||
|
||||
// returns the total size of the index in bytes
|
||||
// Size estimates the memory footprint of the index in bytes
|
||||
// if the underlying faiss index is memory-mapped and not fully loaded into memory.
|
||||
Size() uint64
|
||||
|
||||
// frees the memory associated with the index
|
||||
Close()
|
||||
|
||||
// bPtr returns a pointer to the underlying C index struct.
|
||||
bPtr() *C.FaissIndexBinary
|
||||
|
||||
// CodeSize returns the size of the produced codes in bytes.
|
||||
CodeSize() (uint64, error)
|
||||
}
|
||||
|
||||
type faissBinaryIndex struct {
|
||||
@@ -121,13 +133,13 @@ func (b *faissBinaryIndex) SetDirectMap(mapType int) (err error) {
|
||||
// Applicable only to IVF indexes
|
||||
ivfPtrBinary := C.faiss_IndexBinaryIVF_cast(b.bIdx)
|
||||
if ivfPtrBinary == nil {
|
||||
return errNotBIVFIndex
|
||||
return ErrNotBIVFIndex
|
||||
}
|
||||
if c := C.faiss_IndexBinaryIVF_set_direct_map(
|
||||
ivfPtrBinary,
|
||||
C.int(mapType),
|
||||
); c != 0 {
|
||||
err = getLastError()
|
||||
err = newFaissError(ErrSetParamsFailed, getLastError(), int(c))
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -161,7 +173,7 @@ func (b *faissBinaryIndex) Train(x []uint8) error {
|
||||
n := (len(x) * 8) / b.D()
|
||||
if c := C.faiss_IndexBinary_train(b.bIdx, C.idx_t(n),
|
||||
(*C.uint8_t)(&x[0])); c != 0 {
|
||||
return getLastError()
|
||||
return newFaissError(ErrTrainFailed, getLastError(), int(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -170,7 +182,7 @@ func (b *faissBinaryIndex) Add(x []uint8) error {
|
||||
n := (len(x) * 8) / b.D()
|
||||
if c := C.faiss_IndexBinary_add(b.bIdx, C.idx_t(n),
|
||||
(*C.uint8_t)(&x[0])); c != 0 {
|
||||
return getLastError()
|
||||
return newFaissError(ErrAddFailed, getLastError(), int(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -189,7 +201,7 @@ func (b *faissBinaryIndex) Search(xb []uint8, k int64) (
|
||||
(*C.int32_t)(&distances[0]),
|
||||
(*C.idx_t)(&labels[0]),
|
||||
); c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
return distances, labels, nil
|
||||
}
|
||||
@@ -223,7 +235,7 @@ func (b *faissBinaryIndex) searchWithOptions(xb []uint8, k int64, selector Selec
|
||||
(*C.int32_t)(&distances[0]),
|
||||
(*C.idx_t)(&labels[0]),
|
||||
); c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
return distances, labels, nil
|
||||
}
|
||||
@@ -232,7 +244,7 @@ func (b *faissBinaryIndex) ObtainClusterVectorCountsFromIVFIndex(includedVectors
|
||||
// Applicable only to IVF indexes
|
||||
ivfPtrBinary := C.faiss_IndexBinaryIVF_cast(b.bIdx)
|
||||
if ivfPtrBinary == nil {
|
||||
return nil, errNotBIVFIndex
|
||||
return nil, ErrNotBIVFIndex
|
||||
}
|
||||
// Creating a slice to hold the count of vectors per cluster
|
||||
// Since we have nlist clusters, we create a slice of size nlist
|
||||
@@ -253,7 +265,7 @@ func (b *faissBinaryIndex) ObtainClusterVectorCountsFromIVFIndex(includedVectors
|
||||
C.size_t(nlist),
|
||||
params.sp,
|
||||
); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrInspectIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return listCount, nil
|
||||
}
|
||||
@@ -262,7 +274,7 @@ func (b *faissBinaryIndex) ObtainClustersWithDistancesFromIVFIndex(xb []uint8, i
|
||||
// Applicable only to IVF indexes
|
||||
ivfPtrBinary := C.faiss_IndexBinaryIVF_cast(b.bIdx)
|
||||
if ivfPtrBinary == nil {
|
||||
return nil, nil, errNotBIVFIndex
|
||||
return nil, nil, ErrNotBIVFIndex
|
||||
}
|
||||
params, err := NewStandardSearchParams(includedCentroids)
|
||||
if err != nil {
|
||||
@@ -285,7 +297,7 @@ func (b *faissBinaryIndex) ObtainClustersWithDistancesFromIVFIndex(xb []uint8, i
|
||||
(*C.idx_t)(¢roids[0]),
|
||||
params.sp,
|
||||
); c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return centroids, centroidDistances, nil
|
||||
@@ -300,7 +312,7 @@ func (b *faissBinaryIndex) ObtainKCentroidCardinalitiesFromIVFIndex(limit int, d
|
||||
// Applicable only to IVF indexes
|
||||
ivfPtrBinary := C.faiss_IndexBinaryIVF_cast(b.bIdx)
|
||||
if ivfPtrBinary == nil {
|
||||
return nil, nil, errNotBIVFIndex
|
||||
return nil, nil, ErrNotBIVFIndex
|
||||
}
|
||||
|
||||
nlist := int(C.faiss_IndexBinaryIVF_nlist(ivfPtrBinary))
|
||||
@@ -322,7 +334,7 @@ func (b *faissBinaryIndex) ObtainKCentroidCardinalitiesFromIVFIndex(limit int, d
|
||||
nil,
|
||||
)
|
||||
if c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrInspectIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
topIndices := getIndicesOfKCentroidCardinalities(
|
||||
@@ -347,12 +359,12 @@ func (b *faissBinaryIndex) SearchClustersFromIVFIndex(eligibleCentroidIDs []int6
|
||||
// Applicable only to IVF indexes
|
||||
ivfPtrBinary := C.faiss_IndexBinaryIVF_cast(b.bIdx)
|
||||
if ivfPtrBinary == nil {
|
||||
return nil, nil, errNotBIVFIndex
|
||||
return nil, nil, ErrNotBIVFIndex
|
||||
}
|
||||
// If no include selector is provided, we have no results to return.
|
||||
// return an error indicating that the SearchClustersFromIVFIndex requires a valid selector.
|
||||
if include == nil {
|
||||
return nil, nil, fmt.Errorf("SearchClustersFromIVFIndex requires a valid include selector")
|
||||
return nil, nil, ErrSelectorNil
|
||||
}
|
||||
// create a temporary search params object to set nprobe, this will override
|
||||
// the nprobe and the nlist set at index time, this will allow the search to
|
||||
@@ -396,15 +408,27 @@ func (b *faissBinaryIndex) SearchClustersFromIVFIndex(eligibleCentroidIDs []int6
|
||||
(C.int)(0),
|
||||
searchParams.sp,
|
||||
); c != 0 {
|
||||
return nil, nil, getLastError()
|
||||
return nil, nil, newFaissError(ErrSearchFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return distances, labels, nil
|
||||
}
|
||||
|
||||
func (b *faissBinaryIndex) Size() uint64 {
|
||||
size := C.faiss_IndexBinary_size(b.bIdx)
|
||||
return uint64(size)
|
||||
rv := reflectStaticSizeFaissBinaryIndex
|
||||
var size C.size_t
|
||||
if code := C.faiss_IndexBinary_size(b.bIdx, &size); code == 0 {
|
||||
rv += uint64(size)
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
func (b *faissBinaryIndex) CodeSize() (uint64, error) {
|
||||
var size C.size_t
|
||||
if c := C.faiss_IndexBinary_sa_code_size(b.bIdx, &size); c != 0 {
|
||||
return 0, newFaissError(ErrInspectIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return uint64(size), nil
|
||||
}
|
||||
|
||||
func (idx *faissBinaryIndex) Close() {
|
||||
@@ -423,43 +447,32 @@ func BinaryIndexFactory(dims int, description string) (*BinaryIndexImpl, error)
|
||||
}
|
||||
var idx faissBinaryIndex
|
||||
if c := C.faiss_index_binary_factory(&idx.bIdx, C.int(dims), cDescription); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return &BinaryIndexImpl{&idx}, nil
|
||||
}
|
||||
|
||||
func (idx *faissBinaryIndex) SetQuantizers(srcIndex BinaryIndex) error {
|
||||
bivf := C.faiss_IndexBinaryIVF_cast(idx.bPtr())
|
||||
if bivf == nil {
|
||||
return errNotBIVFIndex
|
||||
if !(idx.IsIVFIndex() && srcIndex.IsIVFIndex()) {
|
||||
return ErrSetQuantizerNotSupported
|
||||
}
|
||||
|
||||
srcIndexPtr := srcIndex.bPtr()
|
||||
if srcIndexPtr == nil {
|
||||
return fmt.Errorf("coarse quantizer is not valid")
|
||||
c := C.faiss_Set_quantizers_binary(idx.bIdx, srcIndex.bPtr())
|
||||
if c != 0 {
|
||||
return newFaissError(ErrSetQuantizerFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
err := C.faiss_Set_quantizers_binary(idx.bIdx, srcIndexPtr)
|
||||
if err != 0 {
|
||||
return fmt.Errorf("faissBinaryIndex err: %w", errFailedToSetQuantizers)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (idx *faissBinaryIndex) MergeFrom(other BinaryIndex, add_id int64) (err error) {
|
||||
if !idx.IsIVFIndex() && !other.IsIVFIndex() {
|
||||
return fmt.Errorf("faissBinaryIndex err: %w", errNotBIVFIndex)
|
||||
if !(idx.IsIVFIndex() && other.IsIVFIndex()) {
|
||||
return ErrMergeFromNotSupported
|
||||
}
|
||||
|
||||
if c := C.faiss_IndexBinaryIVF_merge_from(
|
||||
idx.bPtr(),
|
||||
other.bPtr(),
|
||||
(C.idx_t)(add_id),
|
||||
); c != 0 {
|
||||
err = getLastError()
|
||||
err = newFaissError(ErrMergeFromFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
+1
-1
@@ -21,7 +21,7 @@ func NewIndexFlat(d int, metric int) (*IndexFlat, error) {
|
||||
C.idx_t(d),
|
||||
C.FaissMetricType(metric),
|
||||
); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IndexFlat{&idx}, nil
|
||||
}
|
||||
|
||||
+6
-6
@@ -16,7 +16,7 @@ func WriteIndex(idx Index, filename string) error {
|
||||
cfname := C.CString(filename)
|
||||
defer C.free(unsafe.Pointer(cfname))
|
||||
if c := C.faiss_write_index_fname(idx.cPtr(), cfname); c != 0 {
|
||||
return getLastError()
|
||||
return newFaissError(ErrWriteIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func WriteIndexIntoBuffer(idx Index) ([]byte, error) {
|
||||
&tempBuf,
|
||||
); c != 0 {
|
||||
C.faiss_free_buf(&tempBuf)
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrWriteIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
// at this point, the idx has a valid ref count. furthermore, the index is
|
||||
@@ -89,7 +89,7 @@ func ReadIndexFromBuffer(buf []byte, ioflags int) (*IndexImpl, error) {
|
||||
size,
|
||||
C.int(ioflags),
|
||||
&idx.idx); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrReadIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
ptr = nil
|
||||
@@ -114,7 +114,7 @@ func ReadIndex(filename string, ioflags int) (*IndexImpl, error) {
|
||||
defer C.free(unsafe.Pointer(cfname))
|
||||
var idx faissIndex
|
||||
if c := C.faiss_read_index_fname(cfname, C.int(ioflags), &idx.idx); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrReadIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IndexImpl{&idx}, nil
|
||||
}
|
||||
@@ -130,7 +130,7 @@ func WriteBinaryIndexIntoBuffer(idx BinaryIndex) ([]byte, error) {
|
||||
&tempBuf,
|
||||
); c != 0 {
|
||||
C.faiss_free_buf(&tempBuf)
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrWriteIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
val := unsafe.Slice((*byte)(unsafe.Pointer(tempBuf)), uint(bufSize))
|
||||
@@ -153,7 +153,7 @@ func ReadBinaryIndexFromBuffer(buf []byte, ioflags int) (*BinaryIndexImpl, error
|
||||
size,
|
||||
C.int(ioflags),
|
||||
&bIdx.bIdx); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrReadIndexFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
return &BinaryIndexImpl{&bIdx}, nil
|
||||
|
||||
+8
-18
@@ -9,21 +9,18 @@ package faiss
|
||||
#include <faiss/c_api/IndexScalarQuantizer_c.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (idx *faissIndex) SetDirectMap(mapType int) (err error) {
|
||||
|
||||
ivfPtr := C.faiss_IndexIVF_cast(idx.cPtr())
|
||||
if ivfPtr == nil {
|
||||
return errNotIVFIndex
|
||||
return ErrNotIVFIndex
|
||||
}
|
||||
if c := C.faiss_IndexIVF_set_direct_map(
|
||||
ivfPtr,
|
||||
C.int(mapType),
|
||||
); c != 0 {
|
||||
err = getLastError()
|
||||
err = newFaissError(ErrSetParamsFailed, getLastError(), int(c))
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -32,12 +29,12 @@ func (idx *faissIndex) GetSubIndex() (Index, error) {
|
||||
|
||||
ptr := C.faiss_IndexIDMap2_cast(idx.cPtr())
|
||||
if ptr == nil {
|
||||
return nil, fmt.Errorf("index is not a id map")
|
||||
return nil, ErrNotIDMapIndex
|
||||
}
|
||||
|
||||
subIdx := C.faiss_IndexIDMap2_sub_index(ptr)
|
||||
if subIdx == nil {
|
||||
return nil, fmt.Errorf("couldn't retrieve the sub index")
|
||||
return nil, ErrNotIDMapIndex
|
||||
}
|
||||
|
||||
return &IndexImpl{&faissIndex{subIdx}}, nil
|
||||
@@ -70,18 +67,11 @@ func (idx *faissIndex) IsSQIndex() bool {
|
||||
func (idx *faissIndex) SetQuantizers(srcIndex Index) error {
|
||||
if !(idx.IsIVFIndex() && srcIndex.IsIVFIndex()) &&
|
||||
!(idx.IsSQIndex() && srcIndex.IsSQIndex()) {
|
||||
return fmt.Errorf("faissIndex SetQuantizers: %w, index type not supported", errFailedToSetQuantizers)
|
||||
return ErrSetQuantizerNotSupported
|
||||
}
|
||||
|
||||
srcIndexPtr := srcIndex.cPtr()
|
||||
if srcIndexPtr == nil {
|
||||
return fmt.Errorf("coarse quantizer is not valid")
|
||||
c := C.faiss_Set_quantizers(idx.idx, srcIndex.cPtr())
|
||||
if c != 0 {
|
||||
return newFaissError(ErrSetQuantizerFailed, getLastError(), int(c))
|
||||
}
|
||||
|
||||
err := C.faiss_Set_quantizers(idx.idx, srcIndexPtr)
|
||||
if err != 0 {
|
||||
return fmt.Errorf("faissIndex SetQuantizers: %w", errFailedToSetQuantizers)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+5
-5
@@ -75,7 +75,7 @@ func NewSearchParams(idx Index, params json.RawMessage, selector Selector,
|
||||
rv := &SearchParams{}
|
||||
// Create standard SearchParameters for non-IVF index
|
||||
if c := C.faiss_SearchParameters_new(&rv.sp, sel); c != 0 {
|
||||
return nil, fmt.Errorf("failed to create faiss search params")
|
||||
return nil, ErrCreateParamsFailed
|
||||
}
|
||||
return rv, nil
|
||||
}
|
||||
@@ -133,7 +133,7 @@ func buildIVFSearchParams(maxCodes, nprobe int, sel *C.FaissIDSelector) (*Search
|
||||
C.size_t(nprobe),
|
||||
C.size_t(maxCodes),
|
||||
); c != 0 {
|
||||
return nil, fmt.Errorf("failed to create faiss IVF search params")
|
||||
return nil, ErrCreateParamsFailed
|
||||
}
|
||||
|
||||
return sp, nil
|
||||
@@ -147,7 +147,7 @@ func buildRaBitQSearchParams(maxCodes, nprobe int, sel *C.FaissIDSelector) (*Sea
|
||||
C.size_t(nprobe),
|
||||
C.size_t(maxCodes),
|
||||
); c != 0 {
|
||||
return nil, fmt.Errorf("failed to create faiss IVF RaBitQ search params")
|
||||
return nil, ErrCreateParamsFailed
|
||||
}
|
||||
|
||||
return sp, nil
|
||||
@@ -163,7 +163,7 @@ func NewStandardSearchParams(selector Selector) (*SearchParams, error) {
|
||||
}
|
||||
rv := &SearchParams{}
|
||||
if c := C.faiss_SearchParameters_new(&rv.sp, sel); c != 0 {
|
||||
return nil, fmt.Errorf("failed to create faiss search params")
|
||||
return nil, ErrCreateParamsFailed
|
||||
}
|
||||
return rv, nil
|
||||
}
|
||||
@@ -185,7 +185,7 @@ func NewBinarySearchParams(idx BinaryIndex, params json.RawMessage, selector Sel
|
||||
rv := &SearchParams{}
|
||||
// Create standard SearchParameters for non-IVF index
|
||||
if c := C.faiss_SearchParameters_new(&rv.sp, sel); c != 0 {
|
||||
return nil, fmt.Errorf("failed to create faiss search params")
|
||||
return nil, ErrCreateParamsFailed
|
||||
}
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
+5
-5
@@ -46,7 +46,7 @@ func NewIDSelectorRange(imin, imax int64) (Selector, error) {
|
||||
var sel *C.FaissIDSelectorRange
|
||||
c := C.faiss_IDSelectorRange_new(&sel, C.idx_t(imin), C.idx_t(imax))
|
||||
if c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateSelectorFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IDSelector{sel: (*C.FaissIDSelector)(sel)}, nil
|
||||
}
|
||||
@@ -59,7 +59,7 @@ func NewIDSelectorBatch(indices []int64) (Selector, error) {
|
||||
C.size_t(len(indices)),
|
||||
(*C.idx_t)(&indices[0]),
|
||||
); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateSelectorFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IDSelector{sel: (*C.FaissIDSelector)(sel)}, nil
|
||||
}
|
||||
@@ -78,7 +78,7 @@ func NewIDSelectorBatchNot(exclude []int64) (Selector, error) {
|
||||
batchSelector.Get(),
|
||||
); c != 0 {
|
||||
batchSelector.Delete()
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateSelectorFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IDSelector{exclude: true,
|
||||
sel: (*C.FaissIDSelector)(sel),
|
||||
@@ -98,7 +98,7 @@ func NewIDSelectorBitmap(bitmap []byte) (Selector, error) {
|
||||
C.size_t(len(bitmap)),
|
||||
(*C.uint8_t)(&bitmap[0]),
|
||||
); c != 0 {
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateSelectorFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IDSelector{sel: (*C.FaissIDSelector)(sel)}, nil
|
||||
}
|
||||
@@ -120,7 +120,7 @@ func NewIDSelectorBitmapNot(bitmap []byte) (Selector, error) {
|
||||
bitmapSelector.Get(),
|
||||
); c != 0 {
|
||||
bitmapSelector.Delete()
|
||||
return nil, getLastError()
|
||||
return nil, newFaissError(ErrCreateSelectorFailed, getLastError(), int(c))
|
||||
}
|
||||
return &IDSelector{exclude: true,
|
||||
sel: (*C.FaissIDSelector)(sel),
|
||||
|
||||
+47
@@ -273,3 +273,50 @@ type NestedSegment interface {
|
||||
// a parent document is deleted, all its nested child documents are also considered deleted.
|
||||
AddNestedDocuments(deleted *roaring.Bitmap) *roaring.Bitmap
|
||||
}
|
||||
|
||||
// GeoShapeV2Segment is an optional interface that a Segment may implement
|
||||
// to provide access to GeoShapeV2Data within the segment.
|
||||
type GeoShapeV2Segment interface {
|
||||
Segment
|
||||
|
||||
// GeoShapeV2Data returns the geo shape data for the given field,
|
||||
// excluding any documents present in the except bitmap.
|
||||
GeoShapeV2Data(field string, except *roaring.Bitmap) (GeoShapeV2Data, error)
|
||||
}
|
||||
|
||||
// GeoShapeV2Data provides methods to access separate parts of the GeoShapeV2 data.
|
||||
// Internally, geo docIDs are sequential from 0 to NumDocs()-1; DocNums() maps each
|
||||
// geo docID (the slice index) to its segment document number.
|
||||
type GeoShapeV2Data interface {
|
||||
// InnerCells returns all of the shapes' inner cells in ascending order.
|
||||
InnerCells() []uint64
|
||||
// InnerDocIDs returns the geo docIDs parallel to InnerCells().
|
||||
InnerDocIDs() []uint32
|
||||
// CrossCells returns all of the shapes' cross cells in ascending order.
|
||||
CrossCells() []uint64
|
||||
// CrossDocIDs returns the geo docIDs parallel to CrossCells().
|
||||
CrossDocIDs() []uint32
|
||||
// NumDocs returns the number of documents indexed.
|
||||
NumDocs() uint64
|
||||
// DocNums returns the mapping from geo docID (the slice index) to
|
||||
// segment document number.
|
||||
DocNums() []uint32
|
||||
// DocScores returns the precomputed inner and cross cell scores (in
|
||||
// that order) for the documents indexed, each indexed by geo docID.
|
||||
DocScores() (innerScores, crossScores []uint64)
|
||||
// BoundingBox returns the bounding box bytes for the given geo docID.
|
||||
BoundingBox(geoDocID uint32) ([]byte, error)
|
||||
// Shape returns the shape bytes for the given geo docID.
|
||||
Shape(geoDocID uint32) ([]byte, error)
|
||||
// Excluded returns the bitmap of geo document IDs that are excluded
|
||||
// from the index.
|
||||
Excluded() *roaring.Bitmap
|
||||
// GetScoreMap returns an empty score map, keyed by geo docID, from a
|
||||
// segment-level pool.
|
||||
GetScoreMap() map[uint32]uint64
|
||||
// PutScoreMap clears the score map obtained via GetScoreMap and
|
||||
// returns it to the segment-level pool.
|
||||
PutScoreMap(scores map[uint32]uint64)
|
||||
// Close closes the GeoShapeV2Data and releases any associated resources.
|
||||
Close()
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
package segment
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const StatsKey = "zap_stats"
|
||||
|
||||
type Stats struct {
|
||||
TotNewRootDocsProcessed uint64
|
||||
TotNewDocsProcessed uint64
|
||||
TotNewDocsIndexed uint64
|
||||
TotNewDocsDropped uint64
|
||||
TotNewVectorsProcessed uint64
|
||||
|
||||
TotPersistBeg uint64
|
||||
TotPersistEnd uint64
|
||||
TotPersistErr uint64
|
||||
|
||||
TotMergesBeg uint64
|
||||
TotMergesEnd uint64
|
||||
TotMergesErrors uint64
|
||||
TotMergeInputSegments uint64
|
||||
TotMergeOutputDocs uint64
|
||||
TotMergeDroppedDocs uint64
|
||||
|
||||
TotVecSectionMergesBegin uint64
|
||||
TotVecSectionMergesEnd uint64
|
||||
TotVecSectionMergeErr uint64
|
||||
TotVecSectionMergeTime uint64
|
||||
TotVecSectionVecsReconstructed uint64
|
||||
TotVecSectionIVFIndexesCreated uint64
|
||||
TotVecSectionFlatIndexesCreated uint64
|
||||
TotVecSectionTrainingTime uint64
|
||||
TotVecSectionFastMerges uint64
|
||||
TotVecSectionFastMergeErrs uint64
|
||||
TotVecSectionNaiveMerges uint64
|
||||
TotVecSectionMetadataBytesWritten uint64
|
||||
TotVecSectionFloatIndexBytesWritten uint64
|
||||
TotVecSectionVecsDeleted uint64
|
||||
TotVecSectionFieldsIndexed uint64
|
||||
TotVecSectionTrainOps uint64
|
||||
TotVecSectionIndexWriteTime uint64
|
||||
TotVecSectionVecsProcessedTime uint64
|
||||
|
||||
TotVecSectionTrainingPhaseVecsProcessedTime uint64
|
||||
TotVecSectionTrainingPhaseTrainingTime uint64
|
||||
|
||||
TotOpenBeg uint64
|
||||
TotOpenEnd uint64
|
||||
TotOpenErrors uint64
|
||||
|
||||
TotSegmentsClosed uint64
|
||||
}
|
||||
|
||||
func (s *Stats) StatsMap() map[string]interface{} {
|
||||
svet := reflect.TypeOf(s).Elem()
|
||||
n := svet.NumField()
|
||||
m := make(map[string]interface{}, n)
|
||||
base := unsafe.Pointer(s)
|
||||
for i := 0; i < n; i++ {
|
||||
field := svet.Field(i)
|
||||
|
||||
// use unsafe.Pointer to avoid heap allocs, safe to do this here since all the stats
|
||||
// enforced to be uint64
|
||||
p := (*uint64)(unsafe.Pointer(uintptr(base) + field.Offset))
|
||||
m[field.Name] = atomic.LoadUint64(p)
|
||||
}
|
||||
return m
|
||||
}
|
||||
+20
-3
@@ -20,9 +20,11 @@ import (
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/RoaringBitmap/roaring/v2"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
segment "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
const Version uint32 = 17
|
||||
@@ -32,7 +34,19 @@ const Type string = "zap"
|
||||
const fieldNotUninverted uint64 = math.MaxUint64
|
||||
|
||||
func (sb *SegmentBase) Persist(path string) error {
|
||||
return PersistSegmentBase(sb, path)
|
||||
atomic.AddUint64(&sb.stats.TotPersistBeg, 1)
|
||||
var err error
|
||||
defer func() {
|
||||
atomic.AddUint64(&sb.stats.TotPersistEnd, 1)
|
||||
if err != nil {
|
||||
atomic.AddUint64(&sb.stats.TotPersistErr, 1)
|
||||
}
|
||||
}()
|
||||
err = PersistSegmentBase(sb, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteTo is an implementation of io.WriterTo interface.
|
||||
@@ -99,7 +113,7 @@ func rewriteSegmentBase(sb *SegmentBase, path string) error {
|
||||
closeCh := make(chan struct{})
|
||||
defer close(closeCh)
|
||||
_, _, err := mergeSegmentBases([]*SegmentBase{sb}, []*roaring.Bitmap{nil},
|
||||
path, DefaultChunkMode, closeCh, nil, nil)
|
||||
path, DefaultChunkMode, closeCh, nil, nil, sb.stats)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -186,7 +200,7 @@ func persistStoredFieldValues(fieldID int,
|
||||
|
||||
func InitSegmentBase(mem []byte, memCRC uint32, chunkMode uint32, numDocs uint64,
|
||||
storedIndexOffset uint64, sectionsIndexOffset uint64,
|
||||
config map[string]interface{}) (*SegmentBase, error) {
|
||||
config map[string]interface{}, stats *segment.Stats) (*SegmentBase, error) {
|
||||
sb := &SegmentBase{
|
||||
mem: mem,
|
||||
memCRC: memCRC,
|
||||
@@ -199,12 +213,15 @@ func InitSegmentBase(mem []byte, memCRC uint32, chunkMode uint32, numDocs uint64
|
||||
invIndexCache: newInvertedIndexCache(),
|
||||
vecIndexCache: newVectorIndexCache(),
|
||||
synIndexCache: newSynonymIndexCache(),
|
||||
geoIndexCache: newGeoIndexCache(),
|
||||
nstIndexCache: newNestedIndexCache(),
|
||||
trainedIndexCache: newTrainedIndexCache(),
|
||||
// following fields gets populated by loadFields
|
||||
fieldsMap: make(map[string]uint16),
|
||||
fieldsOptions: make(map[string]index.FieldIndexingOptions),
|
||||
fieldsInv: make([]string, 0),
|
||||
config: config,
|
||||
stats: stats,
|
||||
}
|
||||
sb.updateSize()
|
||||
|
||||
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build vectors
|
||||
// +build vectors
|
||||
|
||||
package zap
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
|
||||
faiss "github.com/blevesearch/go-faiss"
|
||||
)
|
||||
|
||||
func (sb *SegmentBase) GetCoarseQuantizer(field string) (interface{}, error) {
|
||||
fieldIDPlus1 := sb.fieldsMap[field]
|
||||
if fieldIDPlus1 <= 0 {
|
||||
return nil, fmt.Errorf("field %s does not exist in segment", field)
|
||||
}
|
||||
|
||||
vectorSection := sb.fieldsSectionsMap[fieldIDPlus1-1][SectionFaissVectorIndex]
|
||||
// check if the field has a vector section in the segment.
|
||||
if vectorSection <= 0 {
|
||||
return nil, fmt.Errorf("field %s does not have a vector section in the segment", field)
|
||||
}
|
||||
|
||||
pos := int(vectorSection)
|
||||
// doc values and vector optimization type
|
||||
for i := 0; i < 3; i++ {
|
||||
_, n := binary.Uvarint(sb.mem[pos : pos+binary.MaxVarintLen64])
|
||||
pos += n
|
||||
}
|
||||
|
||||
numVecs, n := binary.Uvarint(sb.mem[pos : pos+binary.MaxVarintLen64])
|
||||
pos += n
|
||||
|
||||
// length of the vector to docID map
|
||||
_, n = binary.Uvarint(sb.mem[pos : pos+binary.MaxVarintLen64])
|
||||
pos += n
|
||||
|
||||
// vector to docID mapping
|
||||
for i := 0; i < int(numVecs); i++ {
|
||||
_, n = binary.Uvarint(sb.mem[pos : pos+binary.MaxVarintLen64])
|
||||
pos += n
|
||||
}
|
||||
|
||||
// type of index
|
||||
indexType, n := binary.Uvarint(sb.mem[pos : pos+binary.MaxVarintLen64])
|
||||
pos += n
|
||||
indexSize, n := binary.Uvarint(sb.mem[pos : pos+binary.MaxVarintLen64])
|
||||
pos += n
|
||||
|
||||
// todo: might wanna use the vector cache here, early tests didn't show a big diff
|
||||
faissIndex, err := faiss.ReadIndexFromBuffer(sb.mem[pos:pos+int(indexSize)], faissIOFlags)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pos += int(indexSize)
|
||||
|
||||
if faissIndexType(indexType) == faissBIVFIndex {
|
||||
binaryIndexSize, n := binary.Uvarint(sb.mem[pos : pos+binary.MaxVarintLen64])
|
||||
pos += n
|
||||
binaryIndex, err := faiss.ReadBinaryIndexFromBuffer(sb.mem[pos:pos+int(binaryIndexSize)], faissIOFlags)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newFaissBinaryIndex(binaryIndex, faissIndex)
|
||||
}
|
||||
return newFaissFloat32Index(faissIndex)
|
||||
}
|
||||
+15
-1
@@ -119,9 +119,23 @@ func (d *Dictionary) Contains(key []byte) (bool, error) {
|
||||
// having the the vellum automaton and start/end key range
|
||||
func (d *Dictionary) AutomatonIterator(a segment.Automaton,
|
||||
startKeyInclusive, endKeyExclusive []byte) segment.DictionaryIterator {
|
||||
return d.automatonIterator(a, startKeyInclusive, endKeyExclusive, false)
|
||||
}
|
||||
|
||||
// AutomatonIteratorOmitCount is intended only for candidate-term collection in
|
||||
// fuzzy/prefix queries. It returns an iterator which visits terms in the fst
|
||||
// within the specified start/end key range, but omits the postings list deserialization.
|
||||
func (d *Dictionary) AutomatonIteratorOmitCount(a segment.Automaton,
|
||||
startKeyInclusive, endKeyExclusive []byte) segment.DictionaryIterator {
|
||||
return d.automatonIterator(a, startKeyInclusive, endKeyExclusive, true)
|
||||
}
|
||||
|
||||
func (d *Dictionary) automatonIterator(a segment.Automaton,
|
||||
startKeyInclusive, endKeyExclusive []byte, omitCount bool) segment.DictionaryIterator {
|
||||
if d.fst != nil {
|
||||
rv := &DictionaryIterator{
|
||||
d: d,
|
||||
d: d,
|
||||
omitCount: omitCount,
|
||||
}
|
||||
|
||||
itr, err := d.fst.Search(a, startKeyInclusive, endKeyExclusive)
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
// Copyright (c) 2026 Couchbase, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package zap
|
||||
|
||||
// ewma maintains an exponentially weighted moving average of the number of
|
||||
// hits a cache entry receives per monitoring cycle.
|
||||
type ewma struct {
|
||||
// alpha is the smoothing factor in (0, 1): the weight given to the most
|
||||
// recent sample. Higher values react faster to changes in traffic, lower
|
||||
// values retain history longer.
|
||||
alpha float64
|
||||
// avg is the current moving average of hits per cycle.
|
||||
avg float64
|
||||
// every hit to the cache entry is recorded as part of a sample
|
||||
// which will be used to calculate the average in the next cycle of average
|
||||
// computation (which is average traffic for the field till now). this is
|
||||
// used to track the per second hits to the cache entries.
|
||||
sample uint64
|
||||
}
|
||||
|
||||
// add folds the latest cycle's hit count into the moving average:
|
||||
//
|
||||
// X(t) = a.v + (1 - a).X(t-1)
|
||||
//
|
||||
// The first non-zero sample seeds the average directly rather than being
|
||||
// smoothed from zero. A zero-hit cycle multiplies the average by (1 - alpha),
|
||||
// so an average of 1 hit per cycle decays to exactly (1 - alpha) after one
|
||||
// idle cycle — which is why the cache cleanup passes avg <= (1 - alpha)
|
||||
// as the eviction threshold: it means the entry is averaging less than
|
||||
// one hit per cycle.
|
||||
func (e *ewma) add(val uint64) {
|
||||
if e.avg == 0.0 {
|
||||
e.avg = float64(val)
|
||||
} else {
|
||||
// the exponentially weighted moving average
|
||||
// X(t) = a.v + (1 - a).X(t-1)
|
||||
e.avg = e.alpha*float64(val) + (1-e.alpha)*e.avg
|
||||
}
|
||||
}
|
||||
+162
-87
@@ -25,7 +25,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/RoaringBitmap/roaring/v2"
|
||||
faiss "github.com/blevesearch/go-faiss"
|
||||
seg "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
@@ -63,10 +63,38 @@ func (vc *vectorIndexCache) Clear() {
|
||||
vc.m.Unlock()
|
||||
}
|
||||
|
||||
// vectorCacheOptions controls what loadOrCreate builds and returns.
|
||||
type vectorCacheOptions struct {
|
||||
mem []byte
|
||||
numDocs uint32
|
||||
except *roaring.Bitmap
|
||||
useGPU bool
|
||||
reader *FileReader
|
||||
optStr string
|
||||
|
||||
skipMapping bool // if true, skip building the idMapping
|
||||
stats *seg.Stats
|
||||
}
|
||||
|
||||
func newVectorCacheOptions(mem []byte, numDocs uint32, except *roaring.Bitmap,
|
||||
useGPU bool, reader *FileReader, optStr string, skipMapping bool) *vectorCacheOptions {
|
||||
return &vectorCacheOptions{
|
||||
mem: mem,
|
||||
numDocs: numDocs,
|
||||
except: except,
|
||||
useGPU: useGPU,
|
||||
reader: reader,
|
||||
optStr: optStr,
|
||||
skipMapping: skipMapping,
|
||||
}
|
||||
}
|
||||
|
||||
// loadOrCreate obtains the vector index from the cache or creates it if it's not present.
|
||||
// useGPU indicates whether the field mapping requires GPU acceleration for this index.
|
||||
func (vc *vectorIndexCache) loadOrCreate(fieldID uint16, mem []byte, numDocs uint32, except *roaring.Bitmap, useGPU bool, r *FileReader) (
|
||||
func (vc *vectorIndexCache) loadOrCreate(fieldID uint16, opts *vectorCacheOptions) (
|
||||
index faissIndex, mapping *idMapping, exclude *bitmap, err error) {
|
||||
if opts == nil {
|
||||
return nil, nil, nil, fmt.Errorf("vectorCacheOptions cannot be nil")
|
||||
}
|
||||
// first try to read from the cache with a read lock
|
||||
vc.m.RLock()
|
||||
if vc.isClosed {
|
||||
@@ -77,7 +105,7 @@ func (vc *vectorIndexCache) loadOrCreate(fieldID uint16, mem []byte, numDocs uin
|
||||
entry, ok := vc.cache[fieldID]
|
||||
if ok {
|
||||
vc.m.RUnlock()
|
||||
return entry.load(except)
|
||||
return entry.load(opts.except)
|
||||
}
|
||||
vc.m.RUnlock()
|
||||
// cache miss, rebuild the cache entry under a write lock
|
||||
@@ -90,109 +118,124 @@ func (vc *vectorIndexCache) loadOrCreate(fieldID uint16, mem []byte, numDocs uin
|
||||
// check again if we have the entry now
|
||||
entry, ok = vc.cache[fieldID]
|
||||
if ok {
|
||||
return entry.load(except)
|
||||
return entry.load(opts.except)
|
||||
}
|
||||
// still not present, create and cache it
|
||||
return vc.createAndCacheLOCKED(fieldID, mem, numDocs, except, useGPU, r)
|
||||
return vc.createAndCacheLOCKED(fieldID, opts)
|
||||
}
|
||||
|
||||
// Rebuilding the cache on a miss.
|
||||
func (vc *vectorIndexCache) createAndCacheLOCKED(fieldID uint16, mem []byte,
|
||||
numDocs uint32, except *roaring.Bitmap, useGPU bool, r *FileReader) (index faissIndex,
|
||||
mapping *idMapping, exclude *bitmap, err error) {
|
||||
func readVectorSectionFromFile(opts *vectorCacheOptions) (index faissIndex,
|
||||
mapping *idMapping, err error) {
|
||||
if opts == nil {
|
||||
return nil, nil, fmt.Errorf("vectorCacheOptions cannot be nil")
|
||||
}
|
||||
// if the cache doesn't have the entry, construct the vector to doc id map and
|
||||
// the vector index out of the mem bytes and update the cache under lock.
|
||||
mem := opts.mem
|
||||
pos := 0
|
||||
numVecs, n := binary.Uvarint(mem[pos : pos+binary.MaxVarintLen64])
|
||||
if n <= 0 {
|
||||
return nil, nil, nil, fmt.Errorf("could not read numVecs")
|
||||
}
|
||||
// if no vectors or no documents, return empty cache entry
|
||||
if numVecs == 0 || numDocs == 0 {
|
||||
return nil, nil, nil, nil
|
||||
return nil, nil, fmt.Errorf("could not read numVecs")
|
||||
}
|
||||
pos += n
|
||||
|
||||
// if no vectors or no documents, return empty cache entry
|
||||
if numVecs == 0 || opts.numDocs == 0 {
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
// read the length of the docID list
|
||||
listLen, n := binary.Uvarint(mem[pos : pos+binary.MaxVarintLen64])
|
||||
if n <= 0 {
|
||||
return nil, nil, nil, fmt.Errorf("could not read docID list length")
|
||||
return nil, nil, fmt.Errorf("could not read docID list length")
|
||||
}
|
||||
pos += n
|
||||
// read the entierity of the docID list through the file reader
|
||||
buf, err := r.process(mem[pos : pos+int(listLen)])
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("could not process docID list: %v", err)
|
||||
}
|
||||
listPos := pos
|
||||
pos += int(listLen)
|
||||
bufPos := 0
|
||||
bufLen := len(buf)
|
||||
// create a mapping using the numVecs and numDocs
|
||||
mapping = newIDMapping(uint32(numVecs), numDocs)
|
||||
for vecID := uint32(0); vecID < uint32(numVecs); vecID++ {
|
||||
docID, n := binary.Uvarint(buf[bufPos:min(bufPos+binary.MaxVarintLen64, bufLen)])
|
||||
if n <= 0 {
|
||||
return nil, nil, nil, fmt.Errorf("could not read docID for vecID %d", vecID)
|
||||
|
||||
if !opts.skipMapping {
|
||||
// read the entierity of the docID list through the file reader
|
||||
buf, err := opts.reader.process(mem[listPos : listPos+int(listLen)])
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("could not process docID list: %v", err)
|
||||
}
|
||||
|
||||
bufPos := 0
|
||||
bufLen := len(buf)
|
||||
mapping = newIDMapping(uint32(numVecs), opts.numDocs)
|
||||
for vecID := uint32(0); vecID < uint32(numVecs); vecID++ {
|
||||
docID, n := binary.Uvarint(buf[bufPos:min(bufPos+binary.MaxVarintLen64, bufLen)])
|
||||
if n <= 0 {
|
||||
return nil, nil, fmt.Errorf("could not read docID for vecID %d", vecID)
|
||||
}
|
||||
bufPos += n
|
||||
mapping.add(vecID, uint32(docID))
|
||||
}
|
||||
bufPos += n
|
||||
mapping.add(vecID, uint32(docID))
|
||||
}
|
||||
|
||||
// read the type of the vector index
|
||||
indexType, n := binary.Uvarint(mem[pos : pos+binary.MaxVarintLen64])
|
||||
if n <= 0 {
|
||||
return nil, nil, nil, fmt.Errorf("could not read faiss index type")
|
||||
return nil, nil, fmt.Errorf("could not read faiss index type")
|
||||
}
|
||||
pos += n
|
||||
|
||||
// read the faiss index size
|
||||
indexSize, n := binary.Uvarint(mem[pos : pos+binary.MaxVarintLen64])
|
||||
if n <= 0 {
|
||||
return nil, nil, nil, fmt.Errorf("could not read faiss index size")
|
||||
return nil, nil, fmt.Errorf("could not read faiss index size")
|
||||
}
|
||||
pos += n
|
||||
|
||||
// read the index bytes through the file reader
|
||||
buf, err = r.process(mem[pos : pos+int(indexSize)])
|
||||
fIndexBytes, err := opts.reader.process(mem[pos : pos+int(indexSize)])
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
// read the serialized vector index
|
||||
fIndex, err := faiss.ReadIndexFromBuffer(buf, faissIOFlagsReadOnly)
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("faiss index load error: %v", err)
|
||||
return nil, nil, err
|
||||
}
|
||||
pos += int(indexSize)
|
||||
|
||||
params := newFaissIndexParams(opts.optStr, int(numVecs), 0, faissIOFlagsReadOnly)
|
||||
if faissIndexType(indexType) == faissBIVFIndex {
|
||||
// read the faiss binary index size
|
||||
binSize, n := binary.Uvarint(mem[pos : pos+binary.MaxVarintLen64])
|
||||
pos += n
|
||||
// read the index bytes through the file reader
|
||||
buf, err = r.process(mem[pos : pos+int(binSize)])
|
||||
bIndexBytes, err := opts.reader.process(mem[pos : pos+int(binSize)])
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
// read the serialized binary vector index
|
||||
bIndex, err := faiss.ReadBinaryIndexFromBuffer(buf, faissIOFlagsReadOnly)
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("faiss binary index load error: %v", err)
|
||||
return nil, nil, err
|
||||
}
|
||||
pos += int(binSize)
|
||||
index, err = newFaissBinaryIndex(bIndex, fIndex)
|
||||
index, err = newFaissBinaryIndexFromBytes(bIndexBytes, fIndexBytes, params)
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("faiss binary index creation error: %v", err)
|
||||
return nil, nil, fmt.Errorf("faiss binary index creation error: %v", err)
|
||||
}
|
||||
} else {
|
||||
if useGPU {
|
||||
index, err = newFaissGPUFloat32Index(fIndex)
|
||||
if opts.useGPU {
|
||||
index, err = newFaissGPUFloat32IndexFromBytes(fIndexBytes, params)
|
||||
} else {
|
||||
index, err = newFaissFloat32Index(fIndex)
|
||||
index, err = newFaissFloat32IndexFromBytes(fIndexBytes, params)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("faiss float32 index creation error: %v", err)
|
||||
return nil, nil, fmt.Errorf("faiss float32 index creation error: %v", err)
|
||||
}
|
||||
}
|
||||
// update the cache
|
||||
|
||||
return index, mapping, nil
|
||||
}
|
||||
|
||||
func (vc *vectorIndexCache) createAndCacheLOCKED(fieldID uint16, opts *vectorCacheOptions) (index faissIndex,
|
||||
mapping *idMapping, exclude *bitmap, err error) {
|
||||
if opts == nil {
|
||||
return nil, nil, nil, fmt.Errorf("vectorCacheOptions cannot be nil")
|
||||
}
|
||||
index, mapping, err = readVectorSectionFromFile(opts)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
// update the cache with a complete entry for the fieldID, note that while performing
|
||||
// fast merge we won't be tracking the id mapping since its not relevant
|
||||
vc.insertLOCKED(fieldID, index, mapping)
|
||||
return index, mapping, getExcludedVectors(mapping, except), nil
|
||||
return index, mapping, getExcludedVectors(mapping, opts.except), nil
|
||||
}
|
||||
|
||||
func (vc *vectorIndexCache) insertLOCKED(fieldID uint16,
|
||||
@@ -210,15 +253,6 @@ func (vc *vectorIndexCache) insertLOCKED(fieldID uint16,
|
||||
vc.cache[fieldID] = createCacheEntry(index, mapping, 0.4)
|
||||
}
|
||||
|
||||
func (vc *vectorIndexCache) incHit(fieldID uint16) {
|
||||
vc.m.RLock()
|
||||
entry, ok := vc.cache[fieldID]
|
||||
if ok {
|
||||
entry.incHit()
|
||||
}
|
||||
vc.m.RUnlock()
|
||||
}
|
||||
|
||||
func (vc *vectorIndexCache) decRef(fieldID uint16) {
|
||||
vc.m.RLock()
|
||||
entry, ok := vc.cache[fieldID]
|
||||
@@ -303,28 +337,6 @@ func (vc *vectorIndexCache) monitor() {
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
type ewma struct {
|
||||
alpha float64
|
||||
avg float64
|
||||
// every hit to the cache entry is recorded as part of a sample
|
||||
// which will be used to calculate the average in the next cycle of average
|
||||
// computation (which is average traffic for the field till now). this is
|
||||
// used to track the per second hits to the cache entries.
|
||||
sample uint64
|
||||
}
|
||||
|
||||
func (e *ewma) add(val uint64) {
|
||||
if e.avg == 0.0 {
|
||||
e.avg = float64(val)
|
||||
} else {
|
||||
// the exponentially weighted moving average
|
||||
// X(t) = a.v + (1 - a).X(t-1)
|
||||
e.avg = e.alpha*float64(val) + (1-e.alpha)*e.avg
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
func createCacheEntry(index faissIndex, mapping *idMapping, alpha float64) *cacheEntry {
|
||||
ce := &cacheEntry{
|
||||
index: index,
|
||||
@@ -411,3 +423,66 @@ func getExcludedVectors(idMap *idMapping, except *roaring.Bitmap) (exclude *bitm
|
||||
}
|
||||
return exclude
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
// trainedIndexCache is specifically for caching the trained index in the segment
|
||||
// such that it can be shared and used during fast merge, and avoid putting pressure
|
||||
// on garbage collection
|
||||
type trainedIndexCacheEntry struct {
|
||||
index faissIndex
|
||||
}
|
||||
|
||||
type trainedIndexCache struct {
|
||||
m sync.RWMutex
|
||||
cache map[uint16]*trainedIndexCacheEntry
|
||||
}
|
||||
|
||||
func newTrainedIndexCache() *trainedIndexCache {
|
||||
return &trainedIndexCache{
|
||||
cache: make(map[uint16]*trainedIndexCacheEntry),
|
||||
}
|
||||
}
|
||||
|
||||
func (tc *trainedIndexCache) Clear() {
|
||||
tc.m.Lock()
|
||||
defer tc.m.Unlock()
|
||||
for _, entry := range tc.cache {
|
||||
entry.index.close()
|
||||
}
|
||||
tc.cache = nil
|
||||
}
|
||||
|
||||
func (tc *trainedIndexCache) loadOrCreate(fieldID uint16, opts *vectorCacheOptions) (faissIndex, error) {
|
||||
if opts == nil {
|
||||
return nil, fmt.Errorf("vectorCacheOptions cannot be nil")
|
||||
}
|
||||
tc.m.RLock()
|
||||
entry, ok := tc.cache[fieldID]
|
||||
if ok {
|
||||
tc.m.RUnlock()
|
||||
return entry.index, nil
|
||||
}
|
||||
tc.m.RUnlock()
|
||||
|
||||
tc.m.Lock()
|
||||
defer tc.m.Unlock()
|
||||
|
||||
index, err := tc.createAndCachedLOCKED(fieldID, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return index, nil
|
||||
}
|
||||
|
||||
func (tc *trainedIndexCache) createAndCachedLOCKED(fieldID uint16, opts *vectorCacheOptions) (faissIndex, error) {
|
||||
index, _, err := readVectorSectionFromFile(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tc.cache[fieldID] = &trainedIndexCacheEntry{
|
||||
index: index,
|
||||
}
|
||||
return index, nil
|
||||
}
|
||||
+11
@@ -25,3 +25,14 @@ func newVectorIndexCache() *vectorIndexCache {
|
||||
}
|
||||
|
||||
func (v *vectorIndexCache) Clear() {}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
type trainedIndexCache struct {
|
||||
}
|
||||
|
||||
func newTrainedIndexCache() *trainedIndexCache {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *trainedIndexCache) Clear() {}
|
||||
+62
-1
@@ -20,16 +20,77 @@ package zap
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
|
||||
"github.com/blevesearch/go-faiss"
|
||||
seg "github.com/blevesearch/scorch_segment_api/v2"
|
||||
)
|
||||
|
||||
var (
|
||||
errNilConfig error = errors.New("faiss index config is nil")
|
||||
errNilIndex error = errors.New("faiss index is nil")
|
||||
errNilParams error = errors.New("faiss index params is nil")
|
||||
errNotSupported error = errors.New("operation not supported")
|
||||
)
|
||||
|
||||
var reflectStaticSizeFaissIndexParams uint64
|
||||
|
||||
func init() {
|
||||
var f faissIndexParams
|
||||
reflectStaticSizeFaissIndexParams = uint64(reflect.TypeOf(f).Size())
|
||||
}
|
||||
|
||||
// -------------------------------------------
|
||||
// Parameters for constructing a Faiss index
|
||||
// -------------------------------------------
|
||||
// faissIndexParams holds the construction-time parameters required by a
|
||||
// faissIndex implementation that cannot be derived from the underlying
|
||||
// faiss index objects themselves (e.g. dimension and metric type are
|
||||
// already available on the faiss index).
|
||||
type faissIndexParams struct {
|
||||
// optimization is the index optimization type string (e.g. latency,
|
||||
// recall, memory-efficient, BIVF flavours).
|
||||
optimization string
|
||||
// numVecs is the number of vectors expected to populate the index.
|
||||
// It is needed at construction time because the underlying faiss
|
||||
// index reports zero vectors until trainAndAdd/add is called, but
|
||||
// some construction-time decisions (e.g. whether to clone to GPU)
|
||||
// depend on the eventual vector count.
|
||||
numVecs int
|
||||
// nlist is the number of centroids the index is being built with.
|
||||
// zero during query time.
|
||||
nlist int
|
||||
// ioFlags used to read the index from bytes
|
||||
ioFlags int
|
||||
stats *seg.Stats
|
||||
}
|
||||
|
||||
// newFaissIndexParams constructs a faissIndexParams with the given optimization
|
||||
// type, expected vector count and centroid count.
|
||||
func newFaissIndexParams(optimization string, numVecs, nlist, ioFlags int) *faissIndexParams {
|
||||
return &faissIndexParams{
|
||||
optimization: optimization,
|
||||
numVecs: numVecs,
|
||||
nlist: nlist,
|
||||
ioFlags: ioFlags,
|
||||
}
|
||||
}
|
||||
|
||||
// numTrainingVecs returns how many of the availableVecs vectors to train on.
|
||||
func (p *faissIndexParams) numTrainingVecs(availableVecs int) int {
|
||||
if p.nlist <= 0 {
|
||||
return availableVecs
|
||||
}
|
||||
return min(p.nlist*trainingPointsPerCentroid, availableVecs)
|
||||
}
|
||||
|
||||
func (p *faissIndexParams) size() uint64 {
|
||||
return reflectStaticSizeFaissIndexParams + uint64(len(p.optimization))
|
||||
}
|
||||
|
||||
// -------------------------------------------
|
||||
// Faiss Index Interface
|
||||
// -------------------------------------------
|
||||
|
||||
// Abstract interface for Faiss vector indices, which are returned by the go-faiss library.
|
||||
type faissIndex interface {
|
||||
// adds the given vectors to the index.
|
||||
|
||||
+57
-22
@@ -20,43 +20,74 @@ package zap
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
faiss "github.com/blevesearch/go-faiss"
|
||||
)
|
||||
|
||||
var reflectStaticSizeBinaryIndex uint64
|
||||
|
||||
func init() {
|
||||
var b faissBinaryIndex
|
||||
reflectStaticSizeBinaryIndex = uint64(reflect.TypeOf(b).Size())
|
||||
}
|
||||
|
||||
// ---------------------------------
|
||||
// Faiss Binary IVF Index
|
||||
// ---------------------------------
|
||||
type faissBinaryIndex struct {
|
||||
cfg *faissIndexConfig
|
||||
backing *faiss.IndexImpl
|
||||
binary *faiss.BinaryIndexImpl
|
||||
|
||||
// backingBytes and binaryBytes hold the original serialized index bytes to prevent GC.
|
||||
backingBytes []byte
|
||||
binaryBytes []byte
|
||||
|
||||
params *faissIndexParams
|
||||
}
|
||||
|
||||
func newFaissBinaryIndex(binary *faiss.BinaryIndexImpl, backing *faiss.IndexImpl) (index faissIndex, err error) {
|
||||
func newFaissBinaryIndex(binary *faiss.BinaryIndexImpl, backing *faiss.IndexImpl, params *faissIndexParams) (faissIndex, error) {
|
||||
// we always create this object only with valid backing and binary indexes
|
||||
if binary == nil || backing == nil {
|
||||
return nil, errNilIndex
|
||||
}
|
||||
if params == nil {
|
||||
return nil, errNilParams
|
||||
}
|
||||
return &faissBinaryIndex{
|
||||
backing: backing,
|
||||
binary: binary,
|
||||
params: params,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newFaissBinaryIndexWithConfig(binary *faiss.BinaryIndexImpl, backing *faiss.IndexImpl, cfg *faissIndexConfig) (index faissIndex, err error) {
|
||||
if binary == nil || backing == nil {
|
||||
func newFaissBinaryIndexFromBytes(binaryIndexBytes, backingIndexBytes []byte,
|
||||
params *faissIndexParams) (faissIndex, error) {
|
||||
if binaryIndexBytes == nil || backingIndexBytes == nil {
|
||||
return nil, errNilIndex
|
||||
}
|
||||
if cfg == nil {
|
||||
return nil, errNilConfig
|
||||
|
||||
if params == nil {
|
||||
return nil, errNilParams
|
||||
}
|
||||
|
||||
backing, err := faiss.ReadIndexFromBuffer(backingIndexBytes, params.ioFlags)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
binary, err := faiss.ReadBinaryIndexFromBuffer(binaryIndexBytes, params.ioFlags)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &faissBinaryIndex{
|
||||
cfg: cfg,
|
||||
backing: backing,
|
||||
binary: binary,
|
||||
backing: backing,
|
||||
binary: binary,
|
||||
backingBytes: backingIndexBytes,
|
||||
binaryBytes: binaryIndexBytes,
|
||||
params: params,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -72,6 +103,8 @@ func (b *faissBinaryIndex) add(vecs *vectorSet) error {
|
||||
func (b *faissBinaryIndex) close() {
|
||||
b.binary.Close()
|
||||
b.backing.Close()
|
||||
b.backingBytes = nil
|
||||
b.binaryBytes = nil
|
||||
}
|
||||
|
||||
func (b *faissBinaryIndex) dim() int {
|
||||
@@ -155,7 +188,10 @@ func (b *faissBinaryIndex) write(buf []byte, w *FileWriter) error {
|
||||
}
|
||||
|
||||
func (b *faissBinaryIndex) size() uint64 {
|
||||
return b.binary.Size() + b.backing.Size()
|
||||
return reflectStaticSizeBinaryIndex +
|
||||
b.params.size() +
|
||||
b.backing.Size() +
|
||||
b.binary.Size()
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
@@ -251,16 +287,16 @@ func (b *faissBinaryIndex) setNProbe(nprobe int32) {
|
||||
}
|
||||
|
||||
func (b *faissBinaryIndex) trainAndAdd(trainingData *vectorSet, vecsToAdd *vectorSet) error {
|
||||
// train the backing index with the floatData
|
||||
nvecsToTrain := b.params.numTrainingVecs(trainingData.nvecs)
|
||||
var err error
|
||||
if b.backing.IsSQIndex() {
|
||||
err = b.backing.Train(trainingData.floatData)
|
||||
err = b.backing.Train(trainingData.floatData[:nvecsToTrain*b.dim()])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = b.binary.Train(trainingData.binaryData)
|
||||
err = b.binary.Train(trainingData.binaryData[:nvecsToTrain*(b.dim()/8)])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -287,16 +323,15 @@ func (b *faissBinaryIndex) setQuantizers(trainedIndex faissIndexIVF) error {
|
||||
}
|
||||
|
||||
func (b *faissBinaryIndex) isMergeable() bool {
|
||||
if b.cfg != nil {
|
||||
switch b.cfg.optimizationType {
|
||||
case index.IndexBIVFWithBackingFlat:
|
||||
// the flat backing index currently doesn't support merge_from
|
||||
return false
|
||||
case index.IndexBIVFWithBackingSQ8:
|
||||
return b.backing.Ntotal() > ivfThreshold
|
||||
}
|
||||
switch b.params.optimization {
|
||||
case index.IndexBIVFWithBackingFlat:
|
||||
// the flat backing index currently doesn't support merge_from
|
||||
return false
|
||||
case index.IndexBIVFWithBackingSQ8:
|
||||
return b.params.numVecs >= ivfThreshold
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (b *faissBinaryIndex) mergeFrom(other faissIndex, offset int64) error {
|
||||
|
||||
+45
-22
@@ -20,39 +20,61 @@ package zap
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
faiss "github.com/blevesearch/go-faiss"
|
||||
)
|
||||
|
||||
var reflectStaticSizeFloat32Index uint64
|
||||
|
||||
func init() {
|
||||
var f faissFloat32Index
|
||||
reflectStaticSizeFloat32Index = uint64(reflect.TypeOf(f).Size())
|
||||
}
|
||||
|
||||
// ---------------------------------
|
||||
// Faiss Float32 Index
|
||||
// ---------------------------------
|
||||
type faissFloat32Index struct {
|
||||
cfg *faissIndexConfig
|
||||
idx *faiss.IndexImpl
|
||||
// idxBytes holds the original serialized index bytes to prevent GC.
|
||||
idxBytes []byte
|
||||
params *faissIndexParams
|
||||
}
|
||||
|
||||
func newFaissFloat32Index(idx *faiss.IndexImpl) (index faissIndex, err error) {
|
||||
func newFaissFloat32Index(idx *faiss.IndexImpl, params *faissIndexParams) (faissIndex, error) {
|
||||
if idx == nil {
|
||||
return nil, errNilIndex
|
||||
}
|
||||
if params == nil {
|
||||
return nil, errNilParams
|
||||
}
|
||||
return &faissFloat32Index{
|
||||
idx: idx,
|
||||
idx: idx,
|
||||
params: params,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newFaissFloat32IndexWithConfig(idx *faiss.IndexImpl, cfg *faissIndexConfig) (index faissIndex, err error) {
|
||||
if idx == nil {
|
||||
func newFaissFloat32IndexFromBytes(idxBytes []byte, params *faissIndexParams) (faissIndex, error) {
|
||||
if idxBytes == nil {
|
||||
return nil, errNilIndex
|
||||
}
|
||||
if cfg == nil {
|
||||
return nil, errNilConfig
|
||||
|
||||
if params == nil {
|
||||
return nil, errNilParams
|
||||
}
|
||||
|
||||
idx, err := faiss.ReadIndexFromBuffer(idxBytes, params.ioFlags)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &faissFloat32Index{
|
||||
idx: idx,
|
||||
cfg: cfg,
|
||||
idx: idx,
|
||||
idxBytes: idxBytes,
|
||||
params: params,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -62,6 +84,7 @@ func (f *faissFloat32Index) add(vecs *vectorSet) error {
|
||||
|
||||
func (f *faissFloat32Index) close() {
|
||||
f.idx.Close()
|
||||
f.idxBytes = nil
|
||||
}
|
||||
|
||||
func (f *faissFloat32Index) dim() int {
|
||||
@@ -90,7 +113,7 @@ func (f *faissFloat32Index) write(buf []byte, w *FileWriter) error {
|
||||
return err
|
||||
}
|
||||
idxBytes = w.process(idxBytes)
|
||||
|
||||
atomic.AddUint64(&f.params.stats.TotVecSectionFloatIndexBytesWritten, uint64(len(idxBytes)))
|
||||
// write the length of the serialized vector index bytes
|
||||
n := binary.PutUvarint(buf, uint64(len(idxBytes)))
|
||||
_, err = w.Write(buf[:n])
|
||||
@@ -106,7 +129,9 @@ func (f *faissFloat32Index) write(buf []byte, w *FileWriter) error {
|
||||
}
|
||||
|
||||
func (f *faissFloat32Index) size() uint64 {
|
||||
return f.idx.Size()
|
||||
return reflectStaticSizeFloat32Index +
|
||||
f.params.size() +
|
||||
f.idx.Size()
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
@@ -155,7 +180,8 @@ func (f *faissFloat32Index) setNProbe(nprobe int32) {
|
||||
}
|
||||
|
||||
func (f *faissFloat32Index) trainAndAdd(trainingData *vectorSet, vecsToAdd *vectorSet) error {
|
||||
err := f.idx.Train(trainingData.floatData)
|
||||
nvecsToTrain := f.params.numTrainingVecs(trainingData.nvecs)
|
||||
err := f.idx.Train(trainingData.floatData[:nvecsToTrain*f.dim()])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -173,17 +199,14 @@ func (f *faissFloat32Index) setQuantizers(trainedIndex faissIndexIVF) error {
|
||||
}
|
||||
|
||||
func (f *faissFloat32Index) isMergeable() bool {
|
||||
if f.cfg != nil {
|
||||
switch f.cfg.optimizationType {
|
||||
case index.IndexOptimizedForLatency, index.IndexOptimizedForRecall:
|
||||
return f.ntotal() > ivfSq8Threshold
|
||||
case index.IndexOptimizedForMemoryEfficient, index.IndexIVFRaBitQ:
|
||||
return f.ntotal() > ivfThreshold
|
||||
default:
|
||||
return false
|
||||
}
|
||||
switch f.params.optimization {
|
||||
case index.IndexOptimizedForLatency, index.IndexOptimizedForRecall:
|
||||
return f.params.numVecs >= ivfSq8Threshold
|
||||
case index.IndexOptimizedForMemoryEfficient, index.IndexIVFRaBitQ:
|
||||
return f.params.numVecs >= ivfThreshold
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (f *faissFloat32Index) mergeFrom(other faissIndex, offset int64) error {
|
||||
|
||||
Loaded 100 of 333 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user