-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathqdrant_custom.go
More file actions
657 lines (576 loc) · 16.7 KB
/
qdrant_custom.go
File metadata and controls
657 lines (576 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// Copyright 2025 me.fndo.xb
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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 xb
import (
"encoding/json"
"fmt"
)
// ============================================================================
// QdrantBuilder: Builder Pattern Configuration Builder
// ============================================================================
// QdrantBuilder Qdrant configuration builder
// Uses Builder pattern to construct QdrantCustom configuration
type QdrantBuilder struct {
custom *QdrantCustom
}
// NewQdrantBuilder creates a Qdrant configuration builder
//
// Example:
//
// // Basic configuration
// xb.Of(...).Custom(
// xb.NewQdrantBuilder().
// HnswEf(512).
// ScoreThreshold(0.8).
// Build(),
// ).Build()
//
// // Advanced API
// xb.Of(...).Custom(
// xb.NewQdrantBuilder().
// HnswEf(512).
// Recommend(func(rb *xb.RecommendBuilder) {
// rb.Positive(123, 456).Limit(20)
// }).
// Build(),
// ).Build()
//
// // Mixed configuration
// xb.Of(...).Custom(
// xb.NewQdrantBuilder().
// HnswEf(512).
// ScoreThreshold(0.8).
// Recommend(func(rb *xb.RecommendBuilder) {
// rb.Positive(123, 456).Limit(20)
// }).
// Build(),
// ).Build()
func NewQdrantBuilder() *QdrantBuilder {
return &QdrantBuilder{
custom: newQdrantCustom(),
}
}
// HnswEf sets the ef parameter for HNSW algorithm
// Larger ef means higher query precision but slower speed
// Recommended value: 64-256
func (qb *QdrantBuilder) HnswEf(ef int) *QdrantBuilder {
if ef < 1 {
panic(fmt.Sprintf("HnswEf must be >= 1, got: %d", ef))
}
qb.custom.DefaultHnswEf = ef
return qb
}
// ScoreThreshold sets the minimum similarity threshold
// Only returns results with similarity >= threshold
func (qb *QdrantBuilder) ScoreThreshold(threshold float32) *QdrantBuilder {
if threshold < 0 || threshold > 1 {
panic(fmt.Sprintf("ScoreThreshold must be in [0, 1], got: %f", threshold))
}
qb.custom.DefaultScoreThreshold = threshold
return qb
}
// WithVector sets whether to return vector data
// true: return vectors (uses bandwidth)
// false: don't return vectors (saves bandwidth)
func (qb *QdrantBuilder) WithVector(withVector bool) *QdrantBuilder {
qb.custom.DefaultWithVector = withVector
return qb
}
// Recommend enables Qdrant Recommend API
//
// Example:
//
// xb.NewQdrantBuilder().
// HnswEf(512).
// Recommend(func(rb *xb.RecommendBuilder) {
// rb.Positive(123, 456).Negative(789).Limit(20)
// }).
// Build()
func (qb *QdrantBuilder) Recommend(fn func(rb *RecommendBuilder)) *QdrantBuilder {
if fn == nil {
qb.custom.recommendConfig = nil
return qb
}
builder := &RecommendBuilder{}
fn(builder)
if len(builder.positive) == 0 {
panic("Recommend() requires at least one Positive() id")
}
if builder.limit <= 0 {
panic("Recommend() requires Limit() > 0")
}
qb.custom.recommendConfig = &qdrantRecommendConfig{
positive: append([]int64(nil), builder.positive...),
negative: append([]int64(nil), builder.negative...),
limit: builder.limit,
}
return qb
}
// Discover enables Qdrant Discover API
//
// Example:
//
// xb.NewQdrantBuilder().
// HnswEf(512).
// Discover(func(db *xb.DiscoverBuilder) {
// db.Context(101, 102, 103).Limit(20)
// }).
// Build()
func (qb *QdrantBuilder) Discover(fn func(db *DiscoverBuilder)) *QdrantBuilder {
if fn == nil {
qb.custom.discoverConfig = nil
return qb
}
builder := &DiscoverBuilder{}
fn(builder)
if len(builder.context) == 0 {
panic("Discover() requires Context() with at least one id")
}
if builder.limit <= 0 {
panic("Discover() requires Limit() > 0")
}
qb.custom.discoverConfig = &qdrantDiscoverConfig{
context: append([]int64(nil), builder.context...),
limit: builder.limit,
}
return qb
}
// ScrollID enables Qdrant Scroll API
//
// Example:
//
// xb.NewQdrantBuilder().
// HnswEf(512).
// ScrollID("scroll-abc123").
// Build()
func (qb *QdrantBuilder) ScrollID(scrollID string) *QdrantBuilder {
if scrollID == "" {
panic("ScrollID() requires a non-empty id")
}
qb.custom.scrollID = scrollID
return qb
}
// Build constructs and returns QdrantCustom configuration
func (qb *QdrantBuilder) Build() *QdrantCustom {
return qb.custom
}
// ============================================================================
// QdrantCustom: Qdrant Database-Specific Configuration
// ============================================================================
// QdrantCustom Qdrant-specific configuration implementation
//
// Implements Custom interface, provides Qdrant default configuration and preset modes
type QdrantCustom struct {
// Default parameters (used if user doesn't explicitly specify)
DefaultHnswEf int // Default HNSW EF parameter
DefaultScoreThreshold float32 // Default similarity threshold
DefaultWithVector bool // Default whether to return vectors
// Advanced API configuration (Recommend / Discover / Scroll)
recommendConfig *qdrantRecommendConfig
discoverConfig *qdrantDiscoverConfig
scrollID string
}
// newQdrantCustom internal function: creates Qdrant Custom (default configuration)
func newQdrantCustom() *QdrantCustom {
return &QdrantCustom{
DefaultHnswEf: 128,
DefaultScoreThreshold: 0.0,
DefaultWithVector: false, // Backward compatible: default to not returning vectors
}
}
// Generate implements Custom interface
// ⭐ Returns different JSON based on operation type
func (c *QdrantCustom) Generate(built *Built) (interface{}, error) {
built = c.applyAdvancedConfig(built)
// ⭐ INSERT: generate Qdrant upsert JSON
if built.Inserts != nil && len(*built.Inserts) > 0 {
return c.generateInsertJSON(built)
}
// ⭐ UPDATE: generate Qdrant update payload JSON
if built.Updates != nil && len(*built.Updates) > 0 {
return c.generateUpdateJSON(built)
}
// ⭐ DELETE: generate Qdrant delete JSON
if built.Delete {
return c.generateDeleteJSON(built)
}
// ⭐ SELECT: generate Qdrant search JSON
switch {
case hasBbWithOp(built.Conds, QDRANT_RECOMMEND):
return built.toQdrantRecommendJSON()
case hasBbWithOp(built.Conds, QDRANT_DISCOVER):
return built.toQdrantDiscoverJSON()
case hasBbWithOp(built.Conds, QDRANT_SCROLL):
return built.toQdrantScrollJSON()
default:
json, err := built.toQdrantJSON()
return json, err
}
}
// ============================================================================
// Usage Instructions
// ============================================================================
//
// Configuration methods:
//
// Using QdrantBuilder (unified Builder pattern)
//
// // Basic configuration
// xb.Of(...).Custom(
// xb.NewQdrantBuilder().
// HnswEf(512).
// ScoreThreshold(0.85).
// Build(),
// ).Build()
//
// // Advanced API
// xb.Of(...).Custom(
// xb.NewQdrantBuilder().
// HnswEf(512).
// Recommend(func(rb *xb.RecommendBuilder) {
// rb.Positive(123, 456).Limit(20)
// }).
// Build(),
// ).Build()
//
// // Mixed configuration (basic + advanced)
// xb.Of(...).Custom(
// xb.NewQdrantBuilder().
// HnswEf(512).
// ScoreThreshold(0.85).
// Recommend(func(rb *xb.RecommendBuilder) {
// rb.Positive(123, 456).Limit(20)
// }).
// Build(),
// ).Build()
//
// // Configuration reuse (same configuration can be used for multiple queries)
// highPrecision := xb.NewQdrantBuilder().HnswEf(512).Build()
// xb.Of(...).Custom(highPrecision).Build()
// xb.Of(...).Custom(highPrecision).Build() // Reuse configuration
//
// ============================================================================
// Insert/Update/Delete JSON Generation
// ============================================================================
// QdrantPoint Qdrant point structure
type QdrantPoint struct {
ID interface{} `json:"id"`
Vector interface{} `json:"vector"`
Payload map[string]interface{} `json:"payload,omitempty"`
}
// generateInsertJSON generates Qdrant upsert JSON
// PUT /collections/{collection_name}/points
func (c *QdrantCustom) generateInsertJSON(built *Built) (string, error) {
inserts := *built.Inserts
if len(inserts) == 0 {
return "", fmt.Errorf("no insert data")
}
// Qdrant upsert request structure
type QdrantUpsertRequest struct {
Points []QdrantPoint `json:"points"`
}
points := []QdrantPoint{}
// ⭐ Using Insert(func(ib)) format
// Multiple bbs (field-value pairs) form one point
point, err := c.extractPointFromBbs(inserts)
if err != nil {
return "", err
}
points = append(points, point)
req := QdrantUpsertRequest{Points: points}
bytes, err := json.MarshalIndent(req, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal Qdrant upsert request: %w", err)
}
return string(bytes), nil
}
// generateUpdateJSON generates Qdrant update payload JSON
// POST /collections/{collection_name}/points/payload
func (c *QdrantCustom) generateUpdateJSON(built *Built) (string, error) {
updates := *built.Updates
if len(updates) == 0 {
return "", fmt.Errorf("no update data")
}
// Qdrant update payload request structure
type QdrantUpdateRequest struct {
Points []interface{} `json:"points,omitempty"` // Point ID list
Filter *QdrantFilter `json:"filter,omitempty"` // Or use filter
Payload map[string]interface{} `json:"payload"` // Payload to update
}
// Extract payload
payload := make(map[string]interface{})
for _, bb := range updates {
payload[bb.Key] = bb.Value
}
req := QdrantUpdateRequest{
Payload: payload,
}
// Extract point IDs from conditions or build filter
ids, filter := c.extractIdsOrFilter(built.Conds)
if len(ids) > 0 {
req.Points = ids
} else if filter != nil {
req.Filter = filter
}
bytes, err := json.MarshalIndent(req, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal Qdrant update request: %w", err)
}
return string(bytes), nil
}
// generateDeleteJSON generates Qdrant delete JSON
// POST /collections/{collection_name}/points/delete
func (c *QdrantCustom) generateDeleteJSON(built *Built) (string, error) {
// Qdrant delete request structure
type QdrantDeleteRequest struct {
Points []interface{} `json:"points,omitempty"` // Point ID list
Filter *QdrantFilter `json:"filter,omitempty"` // Or use filter
}
req := QdrantDeleteRequest{}
// Extract point IDs from conditions or build filter
ids, filter := c.extractIdsOrFilter(built.Conds)
if len(ids) > 0 {
req.Points = ids
} else if filter != nil {
req.Filter = filter
} else {
return "", fmt.Errorf("no delete conditions (points or filter)")
}
bytes, err := json.MarshalIndent(req, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal Qdrant delete request: %w", err)
}
return string(bytes), nil
}
// ============================================================================
// Helper Methods
// ============================================================================
// extractPointFromBbs extracts Qdrant Point from InsertBuilder's bbs
// Used for Insert(func(ib *InsertBuilder)) format
func (c *QdrantCustom) extractPointFromBbs(bbs []Bb) (QdrantPoint, error) {
point := QdrantPoint{
Payload: make(map[string]interface{}),
}
for _, bb := range bbs {
switch bb.Key {
case "id":
point.ID = bb.Value
case "vector":
point.Vector = bb.Value
default:
// Other fields go into payload
point.Payload[bb.Key] = bb.Value
}
}
// Validate required fields
if point.ID == nil {
return QdrantPoint{}, fmt.Errorf("point must have 'id' field")
}
if point.Vector == nil {
return QdrantPoint{}, fmt.Errorf("point must have 'vector' field")
}
return point, nil
}
// extractIdsOrFilter extracts point IDs from conditions or builds filter
func (c *QdrantCustom) extractIdsOrFilter(conds []Bb) ([]interface{}, *QdrantFilter) {
ids := []interface{}{}
// Find id IN (...) condition
for _, bb := range conds {
if bb.Key == "id" {
if bb.Op == IN {
// IN condition: extract ID list
if arr, ok := bb.Value.(*[]string); ok {
for _, id := range *arr {
ids = append(ids, id)
}
return ids, nil
}
} else if bb.Op == EQ {
// Single ID
ids = append(ids, bb.Value)
return ids, nil
}
}
}
// If no id condition, build filter
if len(conds) > 0 {
filter := &QdrantFilter{}
filter.Must = []QdrantCondition{}
for _, bb := range conds {
cond := QdrantCondition{
Key: bb.Key,
}
switch bb.Op {
case EQ:
cond.Match = &QdrantMatchCondition{Value: bb.Value}
case GT, GTE, LT, LTE:
cond.Range = &QdrantRangeCondition{}
switch bb.Op {
case GT:
cond.Range.Gt = toFloat64Ptr(bb.Value)
case GTE:
cond.Range.Gte = toFloat64Ptr(bb.Value)
case LT:
cond.Range.Lt = toFloat64Ptr(bb.Value)
case LTE:
cond.Range.Lte = toFloat64Ptr(bb.Value)
}
}
filter.Must = append(filter.Must, cond)
}
return nil, filter
}
return nil, nil
}
func toFloat64Ptr(v interface{}) *float64 {
switch val := v.(type) {
case float64:
return &val
case float32:
f := float64(val)
return &f
case int:
f := float64(val)
return &f
case int64:
f := float64(val)
return &f
}
return nil
}
// qdrantRecommendConfig Recommend API configuration
type qdrantRecommendConfig struct {
positive []int64
negative []int64
limit int
}
// qdrantDiscoverConfig Discover API configuration
type qdrantDiscoverConfig struct {
context []int64
limit int
}
// RecommendBuilder Recommend API builder
type RecommendBuilder struct {
positive []int64
negative []int64
limit int
}
// Positive sets positive sample IDs
func (rb *RecommendBuilder) Positive(ids ...int64) *RecommendBuilder {
if len(ids) == 0 {
return rb
}
rb.positive = append(rb.positive, ids...)
return rb
}
// Negative sets negative sample IDs
func (rb *RecommendBuilder) Negative(ids ...int64) *RecommendBuilder {
if len(ids) == 0 {
return rb
}
rb.negative = append(rb.negative, ids...)
return rb
}
// Limit sets the number of results to return
func (rb *RecommendBuilder) Limit(limit int) *RecommendBuilder {
rb.limit = limit
return rb
}
// DiscoverBuilder Discover API builder
type DiscoverBuilder struct {
context []int64
limit int
}
// Context sets context IDs
func (db *DiscoverBuilder) Context(ids ...int64) *DiscoverBuilder {
if len(ids) == 0 {
return db
}
db.context = append(db.context, ids...)
return db
}
// Limit sets the number of results to return
func (db *DiscoverBuilder) Limit(limit int) *DiscoverBuilder {
db.limit = limit
return db
}
// ensureAdvancedConds injects advanced configuration into condition list
func (c *QdrantCustom) ensureAdvancedConds(conds []Bb) []Bb {
if c == nil {
return conds
}
if c.recommendConfig != nil && !hasBbWithOp(conds, QDRANT_RECOMMEND) {
value := map[string]interface{}{
"positive": append([]int64(nil), c.recommendConfig.positive...),
"limit": c.recommendConfig.limit,
}
if len(c.recommendConfig.negative) > 0 {
value["negative"] = append([]int64(nil), c.recommendConfig.negative...)
}
conds = append(conds, Bb{
Op: QDRANT_RECOMMEND,
Value: value,
})
}
if c.discoverConfig != nil && !hasBbWithOp(conds, QDRANT_DISCOVER) {
value := map[string]interface{}{
"context": append([]int64(nil), c.discoverConfig.context...),
"limit": c.discoverConfig.limit,
}
conds = append(conds, Bb{
Op: QDRANT_DISCOVER,
Value: value,
})
}
if c.scrollID != "" && !hasBbWithOp(conds, QDRANT_SCROLL) {
conds = append(conds, Bb{
Op: QDRANT_SCROLL,
Value: c.scrollID,
})
}
return conds
}
func hasBbWithOp(bbs []Bb, op string) bool {
for _, bb := range bbs {
if bb.Op == op {
return true
}
}
return false
}
func (c *QdrantCustom) applyAdvancedConfig(built *Built) *Built {
if c == nil || built == nil {
return built
}
origLen := len(built.Conds)
condsCopy := cloneBbs(built.Conds)
newConds := c.ensureAdvancedConds(condsCopy)
if len(newConds) == origLen {
return built
}
cloned := *built
cloned.Conds = newConds
return &cloned
}
func cloneBbs(bbs []Bb) []Bb {
if len(bbs) == 0 {
return nil
}
cloned := make([]Bb, len(bbs))
copy(cloned, bbs)
return cloned
}