-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindexing.go
931 lines (827 loc) · 24.2 KB
/
indexing.go
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/charmbracelet/log"
"github.com/hashicorp/go-memdb"
"github.com/meilisearch/meilisearch-go"
g "github.com/zyedidia/generic"
"github.com/zyedidia/generic/set"
"github.com/dofusdude/doduapi/config"
"github.com/dofusdude/doduapi/database"
"github.com/dofusdude/doduapi/utils"
mapping "github.com/dofusdude/dodumap"
)
type SearchStuffType struct {
NameId string `json:"name_id"`
}
type SearchType struct {
Name string `json:"name"` // old "type_name"
NameId string `json:"name_id"` // old "type_id"
}
type SearchIndexedItem struct {
Id int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
SuperType SearchStuffType `json:"super_type"`
Type SearchType `json:"type"`
Level int `json:"level"`
StuffType SearchStuffType `json:"stuff_type"`
}
type SearchIndexedMount struct {
Id int `json:"id"`
Name string `json:"name"`
Family ApiType `json:"family"` // family_name before, now with id and translated name
StuffType SearchStuffType `json:"stuff_type"`
}
type SearchIndexedSet struct {
Id int `json:"id"`
Name string `json:"name"`
Level int `json:"highest_equipment_level"`
ContainsCosmetics bool `json:"contains_cosmetics"`
ContainsCosmeticsOnly bool `json:"contains_cosmetics_only"`
StuffType SearchStuffType `json:"stuff_type"`
}
type EffectConditionDbEntry struct {
Id int
Name string
}
type ItemTypeId struct {
Id int
EnName string
}
func IndexApiData(version *database.VersionT) (*memdb.MemDB, map[string]database.SearchIndexes) {
var items []mapping.MappedMultilangItemUnity
var sets []mapping.MappedMultilangSetUnity
var recipes []mapping.MappedMultilangRecipe
var mounts []mapping.MappedMultilangMount
// --
itemsResponse, err := http.Get(config.ReleaseUrl + "/MAPPED_ITEMS.json")
if err != nil {
log.Fatal(err)
}
itemsBody, err := io.ReadAll(itemsResponse.Body)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(itemsBody, &items)
if err != nil {
log.Fatal(err)
}
// --
setsResponse, err := http.Get(config.ReleaseUrl + "/MAPPED_SETS.json")
if err != nil {
log.Fatal(err)
}
setsBody, err := io.ReadAll(setsResponse.Body)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(setsBody, &sets)
if err != nil {
log.Fatal(err)
}
// --
recipesResponse, err := http.Get(config.ReleaseUrl + "/MAPPED_RECIPES.json")
if err != nil {
log.Fatal(err)
}
recipesBody, err := io.ReadAll(recipesResponse.Body)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(recipesBody, &recipes)
if err != nil {
log.Fatal(err)
}
// --
mountsResponse, err := http.Get(config.ReleaseUrl + "/MAPPED_MOUNTS.json")
if err != nil {
log.Fatal(err)
}
mountsBody, err := io.ReadAll(mountsResponse.Body)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(mountsBody, &mounts)
if err != nil {
log.Fatal(err)
}
log.Debug("loaded", "mounts", len(mounts), "items", len(items), "sets", len(sets), "recipes", len(recipes))
db, indexes := GenerateDatabase(&items, &sets, &recipes, &mounts, version)
return db, indexes
}
func GetMemDBSchema() *memdb.DBSchema {
return &memdb.DBSchema{
Tables: map[string]*memdb.TableSchema{
"red-equipment": {
Name: "red-equipment",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"blue-equipment": {
Name: "blue-equipment",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"red-resources": {
Name: "red-resources",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"blue-resources": {
Name: "blue-resources",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"red-consumables": {
Name: "red-consumables",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"blue-consumables": {
Name: "blue-consumables",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"red-quest_items": {
Name: "red-quest_items",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"blue-quest_items": {
Name: "blue-quest_items",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"red-cosmetics": {
Name: "red-cosmetics",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"blue-cosmetics": {
Name: "blue-cosmetics",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"red-sets": {
Name: "red-sets",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"blue-sets": {
Name: "blue-sets",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"red-all_items": {
Name: "red-all_items",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"blue-all_items": {
Name: "blue-all_items",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"red-recipes": {
Name: "red-recipes",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "ResultId"},
},
},
},
"blue-recipes": {
Name: "blue-recipes",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "ResultId"},
},
},
},
"red-mounts": {
Name: "red-mounts",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
"blue-mounts": {
Name: "blue-mounts",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "AnkamaId"},
},
},
},
// Maybe add red/blue staging here.
"effect-condition-elements": {
Name: "effect-condition-elements",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "Id"},
},
},
},
// Maybe add red/blue staging here.
"item-type-ids": {
Name: "item-type-ids",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.IntFieldIndex{Field: "Id"},
},
},
},
},
}
}
func GetItemSuperType(id int) int {
switch id {
case 1:
return 66230 // Amulett
//case 2: return 66231 // Ring
//case 3: return 66239 // Waffe
//case 4: return 66240 // Zweihandwaffe
}
return 0
}
type AlmanaxBonusListing struct {
Id string `json:"id"` // english-id
Name string `json:"name"` // translated text
}
type AlmanaxBonusListingMeili struct {
Id string `json:"id"` // meili specific id without utf8 guarantees
Slug string `json:"slug"` // english-id
Name string `json:"name"` // translated text
}
func UpdateAlmanaxBonusIndex(init bool) int {
client := meilisearch.New(config.MeiliHost, meilisearch.WithAPIKey(config.MeiliKey))
defer client.Close()
added := 0
for _, lang := range config.Languages {
if lang == "pt" {
continue // no portuguese almanax bonuses
}
url := fmt.Sprintf("https://api.dofusdu.de/dofus2/meta/%s/almanax/bonuses", lang)
resp, err := http.Get(url)
if err != nil {
log.Warn(err, "lang", lang)
return added
}
var bonuses []AlmanaxBonusListing
err = json.NewDecoder(resp.Body).Decode(&bonuses)
if err != nil {
log.Error(err, "lang", lang)
return added
}
var bonusesMeili []AlmanaxBonusListingMeili
var counter int = 0
for i := range bonuses {
bonusesMeili = append(bonusesMeili, AlmanaxBonusListingMeili{
Id: strconv.Itoa(counter),
Slug: bonuses[i].Id,
Name: bonuses[i].Name,
})
counter++
}
indexName := fmt.Sprintf("alm-bonuses-%s", lang)
_, err = client.GetIndex(indexName)
if err != nil {
if strings.Contains(err.Error(), "not found") {
log.Info("alm bonuses index does not exist yet, creating now", "index", indexName)
almTaskInfo, err := client.CreateIndex(&meilisearch.IndexConfig{
Uid: indexName,
PrimaryKey: "id",
})
if err != nil {
log.Error("Error while creating alm bonus index in meili", "err", err)
return added
}
task, err := client.WaitForTask(almTaskInfo.TaskUID, 500*time.Millisecond)
if err != nil {
log.Error("Error while waiting alm bonus index creation at meili", "err", err)
return added
}
if task.Status == "failed" && !strings.Contains(task.Error.Message, "already exists") {
log.Error("alm bonuses creation failed.", "err", task.Error)
return added
}
} else {
log.Error("Error while getting alm bonus index in meili", "err", err)
return added
}
}
almBonusIndex := client.Index(indexName)
if init { // clean index, add all
cleanTask, err := almBonusIndex.DeleteAllDocuments()
if err != nil {
log.Error("Error while cleaning alm bonuses in meili.", "err", err)
return added
}
task, err := client.WaitForTask(cleanTask.TaskUID, 100*time.Millisecond)
if err != nil {
log.Error("Error while waiting for meili to clean alm bonuses.", "err", err)
return added
}
if task.Status == "failed" {
log.Error("clean alm bonuses task failed.", "err", task.Error)
return added
}
var documentsAddTask *meilisearch.TaskInfo
if documentsAddTask, err = almBonusIndex.AddDocuments(bonusesMeili); err != nil {
log.Error("Error while adding alm bonuses to meili.", "err", err)
return added
}
task, err = client.WaitForTask(documentsAddTask.TaskUID, 500*time.Millisecond)
if err != nil {
log.Error("Error while waiting for meili to add alm bonuses.", "err", err)
return added
}
if task.Status == "failed" {
log.Error("alm bonuses add docs task failed.", "err", task.Error)
return added
}
added += len(bonuses)
} else { // search the item exact matches before adding it
for _, bonus := range bonusesMeili {
request := &meilisearch.SearchRequest{
Limit: 1,
}
var searchResp *meilisearch.SearchResponse
if searchResp, err = almBonusIndex.Search(bonus.Name, request); err != nil {
log.Error("SearchAlmanaxBonuses: index not found: ", "err", err)
return added
}
foundIdentical := false
if len(searchResp.Hits) > 0 {
var item = searchResp.Hits[0].(map[string]interface{})
if item["name"] == bonus.Name {
foundIdentical = true
}
}
if !foundIdentical { // add only if not found
log.Info("adding", "bonus", bonus.Name, "bonus", bonus, "lang", lang, "hits", searchResp.Hits)
documentsAddTask, err := almBonusIndex.AddDocuments([]AlmanaxBonusListingMeili{bonus})
if err != nil {
log.Error("Error while adding alm bonuses to meili.", "err", err)
return added
}
task, err := client.WaitForTask(documentsAddTask.TaskUID, 500*time.Millisecond)
if err != nil {
log.Error("Error while waiting for meili to add alm bonuses.", "err", err)
return added
}
if task.Status == "failed" {
log.Error("alm bonuses adding failed.", "err", task.Error)
return added
}
added += 1
}
}
}
}
return added
}
func GenerateDatabase(items *[]mapping.MappedMultilangItemUnity, sets *[]mapping.MappedMultilangSetUnity, recipes *[]mapping.MappedMultilangRecipe, mounts *[]mapping.MappedMultilangMount, version *database.VersionT) (*memdb.MemDB, map[string]database.SearchIndexes) {
/*
item_category_mapping := hashbidimap.New()
item_category_Put(0, 862817) // Ausrüstung
item_category_Put(1, 748369) // Komsumgüter
item_category_Put(2, 67146) // Ressourcen
item_category_Put(3, 67303) // Questgegenstände
item_category_Put(4, 67303) // Questgegenstände -- skipped because internal (hidden without translations)
item_category_Put(5, 764933) // Ausschmückungen
*/
multilangSearchIndexes := make(map[string]database.SearchIndexes)
var indexTasks []*meilisearch.TaskInfo
client := meilisearch.New(config.MeiliHost, meilisearch.WithAPIKey(config.MeiliKey))
defer client.Close()
// generate all indexes with %version-%lang
//meiliPullInterval := 100 * time.Millisecond
updateTasks := make([]*meilisearch.TaskInfo, 0)
for _, lang := range config.Languages {
itemIndexUid := fmt.Sprintf("%s-all_items-%s", utils.NextRedBlueVersionStr(version.Search), lang)
setIndexUid := fmt.Sprintf("%s-sets-%s", utils.NextRedBlueVersionStr(version.Search), lang)
mountIndexUid := fmt.Sprintf("%s-mounts-%s", utils.NextRedBlueVersionStr(version.Search), lang)
createClearIndices([]string{
itemIndexUid,
setIndexUid,
mountIndexUid,
}, client)
// add filters and searchable attributes
// -- all items --
allItemsIdx := client.Index(itemIndexUid)
allItemsFilterTask, err := allItemsIdx.UpdateFilterableAttributes(&[]string{
"super_type.name_id",
"type.name_id",
"level",
})
if err != nil {
log.Fatal(err)
}
updateTasks = append(updateTasks, allItemsFilterTask)
allItemsSearchableTask, err := allItemsIdx.UpdateSearchableAttributes(&[]string{
"name",
"type.name",
"description",
})
if err != nil {
log.Fatal(err)
}
updateTasks = append(updateTasks, allItemsSearchableTask)
// -- mounts --
mountsIdx := client.Index(mountIndexUid)
mountFilterTask, err := mountsIdx.UpdateFilterableAttributes(&[]string{
"family.name",
"family.id",
})
if err != nil {
log.Fatal(err)
}
updateTasks = append(updateTasks, mountFilterTask)
mountSearchableTask, err := mountsIdx.UpdateSearchableAttributes(&[]string{
"name",
"family.name",
})
if err != nil {
log.Fatal(err)
}
updateTasks = append(updateTasks, mountSearchableTask)
// -- sets --
setsIdx := client.Index(setIndexUid)
setFilterUpdateTask, err := setsIdx.UpdateFilterableAttributes(&[]string{
"highest_equipment_level",
"constains_cosmetics",
"constains_cosmetics_only",
})
if err != nil {
log.Fatal(err)
}
updateTasks = append(updateTasks, setFilterUpdateTask)
setSearchableTask, err := setsIdx.UpdateSearchableAttributes(&[]string{
"name",
})
if err != nil {
log.Fatal(err)
}
updateTasks = append(updateTasks, setSearchableTask)
multilangSearchIndexes[lang] = database.SearchIndexes{
AllItems: allItemsIdx,
Sets: setsIdx,
Mounts: mountsIdx,
}
}
wg := sync.WaitGroup{}
wg.Add(1)
go func(tasks []*meilisearch.TaskInfo, client meilisearch.ServiceManager) {
defer wg.Done()
waitForTasks(tasks, client, false)
}(updateTasks, client)
log.Info("waiting for all indexes to be updated")
wg.Wait()
// create in-memory db
schema := GetMemDBSchema()
var err error
var db *memdb.MemDB
if db, err = memdb.NewMemDB(schema); err != nil {
log.Fatal(err)
}
txn := db.Txn(true)
// persistent elements are also in db. TODO does this update automatically?
persIt := config.PersistedElements.Entries.Iterator()
for persIt.Next() {
if err = txn.Insert("effect-condition-elements", &EffectConditionDbEntry{
Id: persIt.Key().(int),
Name: persIt.Value().(string),
}); err != nil {
log.Fatal(err)
}
}
// db prepare insertions
maxBatchSize := 250
itemIndexBatch := make(map[string][]SearchIndexedItem)
itemsTable := fmt.Sprintf("%s-all_items", utils.NextRedBlueVersionStr(version.MemDb))
setsTable := fmt.Sprintf("%s-sets", utils.NextRedBlueVersionStr(version.MemDb))
mountsTable := fmt.Sprintf("%s-mounts", utils.NextRedBlueVersionStr(version.MemDb))
recipesTable := fmt.Sprintf("%s-recipes", utils.NextRedBlueVersionStr(version.MemDb))
for _, recipe := range *recipes {
recipeCt := recipe
if err = txn.Insert(recipesTable, &recipeCt); err != nil {
log.Fatal(err)
}
}
itemTypeIds := set.NewHashset[string](10, g.Equals[string], g.HashString)
// all items search
for _, item := range *items {
itemCp := item
var insertCategoryTable string
if itemCp.Type.CategoryId == 4 {
continue
}
insertCategoryTable = utils.CategoryIdMapping(itemCp.Type.CategoryId)
if err = txn.Insert(fmt.Sprintf("%s-%s", utils.NextRedBlueVersionStr(version.MemDb), insertCategoryTable), &itemCp); err != nil {
log.Fatal(err)
}
if err = txn.Insert(itemsTable, &itemCp); err != nil {
log.Fatal(err)
}
for _, lang := range config.Languages {
enTypeId := strings.ToLower(strings.ReplaceAll(itemCp.Type.Name["en"], " ", "-"))
object := SearchIndexedItem{
Name: itemCp.Name[lang],
Id: itemCp.AnkamaId,
Description: itemCp.Description[lang],
SuperType: SearchStuffType{
NameId: insertCategoryTable,
},
Type: SearchType{
Name: strings.ToLower(itemCp.Type.Name[lang]),
NameId: enTypeId,
},
Level: itemCp.Level,
StuffType: SearchStuffType{
NameId: fmt.Sprintf("items-%s", insertCategoryTable),
},
}
itemTypeIds.Put(enTypeId)
itemIndexBatch[lang] = append(itemIndexBatch[lang], object)
if len(itemIndexBatch[lang]) >= maxBatchSize {
var taskInfo *meilisearch.TaskInfo
if taskInfo, err = multilangSearchIndexes[lang].AllItems.AddDocuments(itemIndexBatch[lang]); err != nil {
log.Fatal(err)
}
indexTasks = append(indexTasks, taskInfo)
itemIndexBatch[lang] = make([]SearchIndexedItem, 0)
}
}
}
// leftover items
for _, lang := range config.Languages {
if len(itemIndexBatch[lang]) > 0 {
var taskInfo *meilisearch.TaskInfo
if taskInfo, err = multilangSearchIndexes[lang].AllItems.AddDocuments(itemIndexBatch[lang]); err != nil {
log.Fatal(err)
}
indexTasks = append(indexTasks, taskInfo)
itemIndexBatch[lang] = make([]SearchIndexedItem, 0)
}
}
for id, itemTypeId := range itemTypeIds.Keys() {
if err = txn.Insert("item-type-ids", &ItemTypeId{
Id: id,
EnName: itemTypeId,
}); err != nil {
log.Fatal(err)
}
}
// sets
setIndexBatch := make(map[string][]SearchIndexedSet)
for _, set := range *sets {
setCp := set
if err := txn.Insert(setsTable, &setCp); err != nil {
log.Fatal(err)
}
for _, lang := range config.Languages {
object := SearchIndexedSet{
Name: setCp.Name[lang],
Id: setCp.AnkamaId,
Level: setCp.Level,
ContainsCosmetics: setCp.ContainsCosmetics,
ContainsCosmeticsOnly: setCp.ContainsCosmeticsOnly,
StuffType: SearchStuffType{
NameId: "sets",
},
}
setIndexBatch[lang] = append(setIndexBatch[lang], object)
if len(setIndexBatch[lang]) >= maxBatchSize {
taskInfo, err := multilangSearchIndexes[lang].Sets.AddDocuments(setIndexBatch[lang])
if err != nil {
log.Fatal(err)
}
indexTasks = append(indexTasks, taskInfo)
setIndexBatch[lang] = nil
}
}
}
// leftover sets
for _, lang := range config.Languages {
if len(setIndexBatch[lang]) > 0 {
var taskInfo *meilisearch.TaskInfo
if taskInfo, err = multilangSearchIndexes[lang].AllItems.AddDocuments(setIndexBatch[lang]); err != nil {
log.Fatal(err)
}
indexTasks = append(indexTasks, taskInfo)
setIndexBatch[lang] = make([]SearchIndexedSet, 0)
}
}
// mounts
mountIndexBatch := make(map[string][]SearchIndexedMount)
for _, mount := range *mounts {
mountCp := mount
if err := txn.Insert(mountsTable, &mountCp); err != nil {
log.Fatal(err)
}
for _, lang := range config.Languages {
object := SearchIndexedMount{
Name: mountCp.Name[lang],
Id: mountCp.AnkamaId,
Family: ApiType{
Name: strings.ToLower(mountCp.FamilyName[lang]),
Id: mountCp.FamilyId,
},
StuffType: SearchStuffType{
NameId: "mounts",
},
}
mountIndexBatch[lang] = append(mountIndexBatch[lang], object)
if len(mountIndexBatch[lang]) >= maxBatchSize {
taskInfo, err := multilangSearchIndexes[lang].Mounts.AddDocuments(mountIndexBatch[lang])
if err != nil {
log.Fatal(err)
}
indexTasks = append(indexTasks, taskInfo)
mountIndexBatch[lang] = nil
}
}
}
// leftover mounts
for _, lang := range config.Languages {
if len(mountIndexBatch[lang]) > 0 {
var taskInfo *meilisearch.TaskInfo
if taskInfo, err = multilangSearchIndexes[lang].AllItems.AddDocuments(mountIndexBatch[lang]); err != nil {
log.Fatal(err)
}
indexTasks = append(indexTasks, taskInfo)
mountIndexBatch[lang] = make([]SearchIndexedMount, 0)
}
}
txn.Commit()
// wait for all indexing tasks to finish
wg.Add(1)
go func(tasks []*meilisearch.TaskInfo, client meilisearch.ServiceManager) {
defer wg.Done()
waitForTasks(tasks, client, false)
}(indexTasks, client)
log.Info("waiting for all documents to be indexed")
wg.Wait()
return db, multilangSearchIndexes
}
func createClearIndices(indexNames []string, client meilisearch.ServiceManager) {
for _, indexName := range indexNames {
index, err := client.GetIndex(indexName)
if err != nil {
if strings.Contains(err.Error(), "not found") {
log.Info("index does not exist yet, creating now", "index", indexName)
taskInfo, err := client.CreateIndex(&meilisearch.IndexConfig{
Uid: indexName,
PrimaryKey: "id",
})
if err != nil {
log.Error("Error while creating index in meili", "err", err)
return
}
task, err := client.WaitForTask(taskInfo.TaskUID, 100*time.Millisecond)
if err != nil {
log.Error("Error while waiting index creation at meili", "err", err)
return
}
if task.Status != meilisearch.TaskStatusSucceeded {
log.Error("Meili", "status", task.Status, "message", task.Error.Message)
}
} else {
log.Error("Error while getting index in meili", "err", err)
return
}
} else { // clear index and start over
log.Info("index exists, clearing", "index", indexName)
delTask, err := index.DeleteAllDocuments()
task, err := client.WaitForTask(delTask.TaskUID, 100*time.Millisecond)
if err != nil {
log.Error("Error while waiting index creation at meili", "err", err)
return
}
if task.Status != meilisearch.TaskStatusSucceeded {
log.Error("Meili", "status", task.Status, "message", task.Error.Message)
}
}
}
}
func waitForTasks(tasks []*meilisearch.TaskInfo, client meilisearch.ServiceManager, ignoreExists bool) {
if len(tasks) == 0 {
return
}
wg := sync.WaitGroup{}
semap := make(chan struct{}, runtime.NumCPU()*2)
for _, task := range tasks {
wg.Add(1)
go func(taskInfo *meilisearch.TaskInfo, client meilisearch.ServiceManager) {
defer wg.Done()
semap <- struct{}{}
defer func() {
<-semap
}()
task, err := client.WaitForTask(taskInfo.TaskUID, 100*time.Millisecond)
if err != nil {
log.Fatal(err)
}
if ignoreExists && task.Status == meilisearch.TaskStatusFailed && !strings.Contains(task.Error.Message, "already exists") {
return
}
if task.Status != meilisearch.TaskStatusSucceeded {
log.Error("Meili", "status", task.Status, "message", task.Error.Message)
}
}(task, client)
}
wg.Wait()
}