/
search.go
881 lines (816 loc) · 24.9 KB
/
search.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
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package charmstore // import "gopkg.in/juju/charmstore.v5/internal/charmstore"
import (
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
"strings"
"time"
"github.com/juju/charmrepo/v6/csclient/params"
"github.com/juju/utils"
"gopkg.in/errgo.v1"
"gopkg.in/mgo.v2/bson"
"gopkg.in/juju/charmstore.v5/elasticsearch"
"gopkg.in/juju/charmstore.v5/internal/charm"
"gopkg.in/juju/charmstore.v5/internal/entitycache"
"gopkg.in/juju/charmstore.v5/internal/mongodoc"
"gopkg.in/juju/charmstore.v5/internal/router"
"gopkg.in/juju/charmstore.v5/internal/series"
)
type SearchIndex struct {
*elasticsearch.Database
Index string
}
const typeName = "entity"
// seriesBoost defines how much the results for each
// series will be boosted. Series are currently ranked in
// reverse order of LTS releases, followed by the latest
// non-LTS release, followed by everything else.
var seriesBoost = func() map[string]float64 {
m := make(map[string]float64)
for k, v := range series.Series {
if !v.SearchIndex {
continue
}
m[k] = v.SearchBoost
}
return m
}()
// SearchDoc is a mongodoc.Entity with additional fields useful for searching.
// This is the document that is stored in the search index.
type SearchDoc struct {
*mongodoc.Entity
TotalDownloads int64
ReadACLs []string
Series []string
// SingleSeries is true if the document referes to an entity that
// describes a single series. This will either be a bundle, a
// single-series charm or an expanded record for a multi-series
// charm.
SingleSeries bool
// AllSeries is true if the document referes to an entity that
// describes all series supported by the entity. This will either
// be a bundle, a single-series charm or the canonical record for
// a multi-series charm.
AllSeries bool
}
// UpdateSearchAsync will update the search record for the entity
// reference r in the backgroud.
func (s *Store) UpdateSearchAsync(r *router.ResolvedURL) {
s.Go(func(s *Store) {
if err := s.UpdateSearch(r); err != nil {
logger.Errorf("cannot update search record for %v: %s", r, err)
}
})
}
// UpdateSearch updates the search record for the entity reference r. The
// search index only includes the latest stable revision of each entity
// so the latest stable revision of the charm specified by r will be
// indexed.
func (s *Store) UpdateSearch(r *router.ResolvedURL) error {
if s.ES == nil || s.ES.Database == nil {
return nil
}
// For multi-series charms update the whole base URL.
if r.URL.Series == "" {
return s.UpdateSearchBaseURL(&r.URL)
}
if !series.Series[r.URL.Series].SearchIndex {
return nil
}
baseEntity, err := s.FindBaseEntity(&r.URL, nil)
if err != nil {
return errgo.NoteMask(err, fmt.Sprintf("cannot update search record for %q", &r.URL), errgo.Is(params.ErrNotFound))
}
series := r.URL.Series
entityURL := baseEntity.ChannelEntities[params.StableChannel][series]
if entityURL == nil {
// There is no stable version of the entity to index.
return nil
}
entity, err := s.FindEntity(&router.ResolvedURL{URL: *entityURL}, nil)
if err != nil {
return errgo.Notef(err, "cannot update search record for %q", entityURL)
}
if err := s.updateSearchEntity(entity, baseEntity); err != nil {
return errgo.Notef(err, "cannot update search record for %q", entityURL)
}
return nil
}
// UpdateSearchBaseURL updates the search record for all entities with
// the specified base URL. It must be called whenever the entry for the
// given URL in the BaseEntitites collection has changed.
func (s *Store) UpdateSearchBaseURL(baseURL *charm.URL) error {
if s.ES == nil || s.ES.Database == nil {
return nil
}
baseEntity, err := s.FindBaseEntity(baseURL, nil)
if err != nil {
return errgo.NoteMask(err, fmt.Sprintf("cannot index %s", baseURL), errgo.Is(params.ErrNotFound))
}
stableEntities := baseEntity.ChannelEntities[params.StableChannel]
updated := make(map[string]bool, len(stableEntities))
for urlSeries, url := range stableEntities {
if !series.Series[urlSeries].SearchIndex {
continue
}
if updated[url.String()] {
continue
}
updated[url.String()] = true
entity, err := s.FindEntity(&router.ResolvedURL{URL: *url}, nil)
if err != nil {
return errgo.Notef(err, "cannot update search record for %q", url)
}
if err := s.updateSearchEntity(entity, baseEntity); err != nil {
return errgo.Notef(err, "cannot update search record for %q", url)
}
}
return nil
}
func (s *Store) updateSearchEntity(entity *mongodoc.Entity, baseEntity *mongodoc.BaseEntity) error {
doc, err := s.searchDocFromEntity(entity, baseEntity)
if err != nil {
return errgo.Mask(err)
}
if err := s.ES.update(doc); err != nil {
return errgo.Notef(err, "cannot update search index")
}
return nil
}
// searchDocFromEntity performs the processing required to convert a
// mongodoc.Entity and the corresponding mongodoc.BaseEntity to an esDoc
// for indexing.
func (s *Store) searchDocFromEntity(e *mongodoc.Entity, be *mongodoc.BaseEntity) (*SearchDoc, error) {
doc := SearchDoc{Entity: e}
doc.ReadACLs = be.ChannelACLs[params.StableChannel].Read
// There should only be one record for the promulgated entity, which
// should be the latest promulgated revision. In the case that the base
// entity is not promulgated assume that there is a later promulgated
// entity.
if !be.Promulgated {
doc.Entity.PromulgatedURL = nil
doc.Entity.PromulgatedRevision = -1
}
rid := EntityResolvedURL(e)
url := rid.PromulgatedURL()
if url == nil {
url = &rid.URL
}
_, allRevisions, err := s.ArchiveDownloadCounts(url)
if err != nil {
return nil, errgo.Mask(err)
}
doc.TotalDownloads = allRevisions.Total
if doc.Entity.Series == "bundle" {
doc.Series = []string{"bundle"}
} else {
doc.Series = doc.Entity.SupportedSeries
}
doc.AllSeries = true
doc.SingleSeries = doc.Entity.Series != ""
return &doc, nil
}
// update inserts an entity into elasticsearch if elasticsearch
// is configured. The entity with id r is extracted from mongodb
// and written into elasticsearch.
func (si *SearchIndex) update(doc *SearchDoc) error {
if si == nil || si.Database == nil {
return nil
}
err := si.PutDocumentVersionWithType(
si.Index,
typeName,
si.getID(doc.URL),
int64(doc.URL.Revision),
elasticsearch.ExternalGTE,
doc)
if err != nil && !elasticsearch.IsConflictError(errgo.Cause(err)) {
return errgo.Mask(err)
}
if doc.Entity.URL.Series != "" {
return nil
}
// This document represents a multi-series charm. Expand the
// document for each of the supported series.
for _, series := range doc.Entity.SupportedSeries {
u := *doc.Entity.URL
u.Series = series
doc.Entity.URL = &u
if doc.PromulgatedURL != nil {
u := *doc.Entity.PromulgatedURL
u.Series = series
doc.Entity.PromulgatedURL = &u
}
doc.Series = []string{series}
doc.AllSeries = false
doc.SingleSeries = true
if err := si.update(doc); err != nil {
return errgo.Mask(err)
}
}
return nil
}
// getID returns an ID for the elasticsearch document based on the contents of the
// mongoDB document. This is to allow elasticsearch documents to be replaced with
// updated versions when charm data is changed.
func (si *SearchIndex) getID(r *charm.URL) string {
ref := *r
ref.Revision = -1
b := sha1.Sum([]byte(ref.String()))
s := base64.URLEncoding.EncodeToString(b[:])
// Cut off any trailing = as there is no need for them and they will get URL escaped.
return strings.TrimRight(s, "=")
}
// GetSearchDocument retrieves the current search record for the charm
// reference id.
func (si *SearchIndex) GetSearchDocument(id *charm.URL) (*SearchDoc, error) {
if si == nil || si.Database == nil {
return &SearchDoc{}, nil
}
var s SearchDoc
err := si.GetDocument(si.Index, "entity", si.getID(id), &s)
if err != nil {
return nil, errgo.Notef(err, "cannot retrieve search document for %v", id)
}
return &s, nil
}
// version is a document that stores the structure information
// in the elasticsearch database.
type version struct {
Version int64
Index string
}
const versionIndex = ".versions"
const versionType = "version"
// ensureIndexes makes sure that the required indexes exist and have the right
// settings. If force is true then ensureIndexes will create new indexes irrespective
// of the status of the current index.
func (si *SearchIndex) ensureIndexes(force bool) error {
if si == nil || si.Database == nil {
return nil
}
old, dv, err := si.getCurrentVersion()
if err != nil {
return errgo.Notef(err, "cannot get current version")
}
if !force && old.Version >= esSettingsVersion {
return nil
}
index, err := si.newIndex()
if err != nil {
return errgo.Notef(err, "cannot create index")
}
new := version{
Version: esSettingsVersion,
Index: index,
}
updated, err := si.updateVersion(new, dv)
if err != nil {
return errgo.Notef(err, "cannot update version")
}
if !updated {
// Update failed so delete the new index
if err := si.DeleteIndex(index); err != nil {
return errgo.Notef(err, "cannot delete index")
}
return nil
}
// Update succeeded - update the aliases
if err := si.Alias(index, si.Index); err != nil {
return errgo.Notef(err, "cannot create alias")
}
// Delete the old unused index
if old.Index != "" {
if err := si.DeleteIndex(old.Index); err != nil {
return errgo.Notef(err, "cannot delete index")
}
}
return nil
}
// getCurrentVersion gets the version of elasticsearch settings, if any
// that are deployed to elasticsearch.
func (si *SearchIndex) getCurrentVersion() (version, int64, error) {
var v version
d, err := si.GetESDocument(versionIndex, versionType, si.Index)
if err != nil && !elasticsearch.IsNotFoundError(errgo.Cause(err)) {
return version{}, 0, errgo.Notef(err, "cannot get settings version")
}
if d.Found {
if err := json.Unmarshal(d.Source, &v); err != nil {
return version{}, 0, errgo.Notef(err, "invalid version")
}
}
return v, d.Version, nil
}
// newIndex creates a new index with current elasticsearch settings.
// The new Index will have a randomized name based on si.Index.
func (si *SearchIndex) newIndex() (string, error) {
uuid, err := utils.NewUUID()
if err != nil {
return "", errgo.Notef(err, "cannot create index name")
}
index := si.Index + "-" + uuid.String()
if err := si.PutIndex(index, esIndex); err != nil {
return "", errgo.Notef(err, "cannot set index settings")
}
if err := si.PutMapping(index, "entity", esMapping); err != nil {
return "", errgo.Notef(err, "cannot set index mapping")
}
return index, nil
}
// updateVersion attempts to atomically update the document specifying the version of
// the elasticsearch settings. If it succeeds then err will be nil, if the update could not be
// made atomically then err will be elasticsearch.ErrConflict, otherwise err is a non-nil
// error.
func (si *SearchIndex) updateVersion(v version, dv int64) (bool, error) {
var err error
if dv == 0 {
err = si.CreateDocument(versionIndex, versionType, si.Index, v)
} else {
err = si.PutDocumentVersion(versionIndex, versionType, si.Index, dv, v)
}
if err != nil {
if elasticsearch.IsConflictError(errgo.Cause(err)) {
return false, nil
}
return false, err
}
return true, nil
}
// syncSearch populates the SearchIndex with all the data currently stored in
// mongodb. If the SearchIndex is not configured then this method returns a nil error.
func (s *Store) syncSearch() error {
if s.ES == nil || s.ES.Database == nil {
return nil
}
var result mongodoc.Entity
// Only get the IDs here, UpdateSearch will get the full document
// if it is in a series that is indexed.
iter := s.DB.Entities().Find(nil).Select(bson.M{"_id": 1, "promulgated-url": 1}).Iter()
defer iter.Close() // Make sure we always close on error.
for iter.Next(&result) {
rurl := EntityResolvedURL(&result)
if err := s.UpdateSearch(rurl); err != nil {
return errgo.Notef(err, "cannot index %s", rurl)
}
}
logger.Infof("finished sync search")
if err := iter.Close(); err != nil {
return err
}
return nil
}
// SearchParams represents the search parameters used to search the store.
type SearchParams struct {
// The text to use in the full text search query.
Text string
// If autocomplete is specified, the search will return only charms and
// bundles with a name that has text as a prefix.
AutoComplete bool
// Limit the search to items with attributes that match the specified filter value.
Filters map[string][]string
// Limit the number of returned items to the specified count.
Limit int
// Include the following metadata items in the search results.
Include []string
// Start the the returned items at a specific offset.
Skip int
// ACL values to search in addition to everyone. ACL values may represent user names
// or group names.
Groups []string
// Admin searches will not filter on the ACL and will show results for all matching
// charms.
Admin bool
// Sort the returned items.
Sort []SortParam
// ExpandedMultiSeries returns a number of entries for
// multi-series charms, one for each entity.
ExpandedMultiSeries bool
}
var allowedSortFields = map[string]bool{
"name": true,
"owner": true,
"series": true,
"downloads": true,
}
func (sp *SearchParams) ParseSortFields(f ...string) error {
for _, s := range f {
for _, s := range strings.Split(s, ",") {
var sort SortParam
if strings.HasPrefix(s, "-") {
sort.Descending = true
s = s[1:]
}
if !allowedSortFields[s] {
return errgo.Newf("unrecognized sort parameter %q", s)
}
sort.Field = s
sp.Sort = append(sp.Sort, sort)
}
}
return nil
}
// sortOrder defines the order in which a field should be sorted.
type sortOrder int
// SortParam represents a field and direction on which results should be sorted.
type SortParam struct {
Field string
Descending bool
}
// SearchQuery represents a query on the elasticsearch index.
type SearchQuery struct {
index *SearchIndex
params SearchParams
total int
duration time.Duration
}
// Total returns the total number of hits found in the index. This will
// only be correct after the iteration has completed successfully.
func (q *SearchQuery) Total() int {
return q.total
}
// Duration returns the total time spent searching the index. This will
// only be correct after the iteration has completed successfully.
func (q *SearchQuery) Duration() time.Duration {
return q.duration
}
// Iter returns a new StoreIter to iterate through the results of the
// query. The returned StoreIter will be an instance of SearchQueryIter.
func (q *SearchQuery) Iter(fields map[string]int) entitycache.StoreIter {
if q.index == nil || q.index.Database == nil {
return new(searchQueryIter)
}
qdsl := createSearchDSL(q.params)
qdsl.Source = elasticsearch.SourceFilter{
"AllSeries",
"SingleSeries",
}
for k := range fields {
f, ok := searchFields[k]
if !ok {
logger.Warningf("unknown field %q requested", k)
continue
}
qdsl.Source = append(qdsl.Source, f)
}
result, err := q.index.Search(q.index.Index, typeName, qdsl)
q.total = result.Hits.Total
q.duration = time.Duration(result.Took) * time.Millisecond
return &searchQueryIter{
result: result,
err: err,
}
}
type searchQueryIter struct {
n int
result elasticsearch.SearchResult
err error
}
func (i *searchQueryIter) Err() error {
return i.err
}
func (i *searchQueryIter) Close() error {
return i.err
}
func (i *searchQueryIter) Next(v interface{}) bool {
if i.n >= len(i.result.Hits.Hits) || i.err != nil {
return false
}
var doc SearchDoc
if err := json.Unmarshal(i.result.Hits.Hits[i.n].Source, &doc); err != nil {
i.err = errgo.Mask(err)
return false
}
e := v.(*mongodoc.Entity)
*e = *doc.Entity
if doc.SingleSeries && doc.AllSeries && len(doc.Series) > 0 {
e.Series = doc.Series[0]
}
i.n++
return true
}
// ListResult represents the result of performing a list.
type ListResult struct {
Results []*mongodoc.Entity
}
// encodeFields takes a map of field name to weight and builds a slice of strings
// representing those weighted fields for a MultiMatchQuery.
func encodeFields(fields map[string]float64) []string {
fs := make([]string, 0, len(fields))
for k, v := range fields {
fs = append(fs, elasticsearch.BoostField(k, v))
}
return fs
}
// createSearchDSL builds an elasticsearch query from the query parameters.
// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html
func createSearchDSL(sp SearchParams) elasticsearch.QueryDSL {
qdsl := elasticsearch.QueryDSL{
From: sp.Skip,
Size: sp.Limit,
}
// Full text search
var q elasticsearch.Query
nameField := "Name.tok"
if sp.AutoComplete {
nameField = "Name.ngrams"
}
if sp.Text == "" {
q = elasticsearch.MatchAllQuery{}
} else {
q = elasticsearch.MultiMatchQuery{
Query: sp.Text,
Fields: encodeFields(map[string]float64{
nameField: 10,
"User.tok": 7,
"CharmMeta.Categories.tok": 5,
"CharmMeta.Tags.tok": 5,
"BundleData.Tags.tok": 5,
}),
MinimumShouldMatch: "100%",
}
}
// Boosting
f := []elasticsearch.Function{
// TODO(mhilton) review this function in future if downloads get sufficiently
// large that the order becomes undesirable.
elasticsearch.FieldValueFactorFunction{
Field: "TotalDownloads",
Factor: 0.000001,
Modifier: "ln2p",
},
elasticsearch.BoostFactorFunction{
Filter: promulgatedFilter("1"),
BoostFactor: 1.25,
},
}
for k, v := range seriesBoost {
f = append(f, elasticsearch.BoostFactorFunction{
Filter: seriesFilter(k),
BoostFactor: v,
})
}
q = elasticsearch.FunctionScoreQuery{
Query: q,
Functions: f,
}
// Filters
qdsl.Query = elasticsearch.FilteredQuery{
Query: q,
Filter: createFilters(sp),
}
// Sorting
for _, s := range sp.Sort {
qdsl.Sort = append(qdsl.Sort, createElasticSort(s))
}
return qdsl
}
// createFilters converts the filters requested with the search API into
// filters in the elasticsearch query DSL.
// See https://github.com/juju/charmstore/blob/v4/docs/API.md#get-search
// for details of how filters are specified in the API. For each key in f a
// filter is created that matches any one of the set of values specified for
// that key. The created filter will only match when at least one of the
// requested values matches for all of the requested keys. Any filter names
// that are not defined in the filters map will be silently skipped
func createFilters(sp SearchParams) elasticsearch.Filter {
af := make(elasticsearch.AndFilter, 1, len(sp.Filters)+2)
if sp.ExpandedMultiSeries {
af[0] = elasticsearch.TermFilter{
Field: "SingleSeries",
Value: "true",
}
} else {
af[0] = elasticsearch.TermFilter{
Field: "AllSeries",
Value: "true",
}
}
for k, vals := range sp.Filters {
filter, ok := filters[k]
if !ok {
continue
}
of := make(elasticsearch.OrFilter, 0, len(vals))
for _, v := range vals {
of = append(of, filter(v))
}
af = append(af, of)
}
if sp.Admin {
return af
}
gf := make(elasticsearch.OrFilter, 0, len(sp.Groups)+1)
gf = append(gf, elasticsearch.TermFilter{
Field: "ReadACLs",
Value: params.Everyone,
})
for _, g := range sp.Groups {
gf = append(gf, elasticsearch.TermFilter{
Field: "ReadACLs",
Value: g,
})
}
af = append(af, gf)
return af
}
// filters contains a mapping from a filter parameter in the API to a
// function that will generate an elasticsearch query DSL filter for the
// given value.
var filters = map[string]func(string) elasticsearch.Filter{
"description": descriptionFilter,
"name": nameFilter,
"owner": ownerFilter,
"promulgated": promulgatedFilter,
"provides": termFilter("CharmProvidedInterfaces"),
"requires": termFilter("CharmRequiredInterfaces"),
"series": seriesFilter,
"summary": summaryFilter,
"tags": tagsFilter,
"type": typeFilter,
}
// descriptionFilter generates a filter that will match against the
// description field of the charm data.
func descriptionFilter(value string) elasticsearch.Filter {
return elasticsearch.QueryFilter{
Query: elasticsearch.MatchQuery{
Field: "CharmMeta.Description",
Query: value,
Type: "phrase",
},
}
}
// nameFilter generates a filter that will match against the
// name of the charm or bundle.
func nameFilter(value string) elasticsearch.Filter {
return elasticsearch.QueryFilter{
Query: elasticsearch.MatchQuery{
Field: "Name",
Query: value,
Type: "phrase",
},
}
}
// ownerFilter generates a filter that will match against the
// owner taken from the URL.
func ownerFilter(value string) elasticsearch.Filter {
if value == "" {
return promulgatedFilter("1")
}
return elasticsearch.QueryFilter{
Query: elasticsearch.MatchQuery{
Field: "User",
Query: value,
Type: "phrase",
},
}
}
// promulgatedFilter generates a filter that will match against the
// existence of a promulgated URL.
func promulgatedFilter(value string) elasticsearch.Filter {
f := elasticsearch.ExistsFilter("PromulgatedURL")
if value == "1" {
return f
}
return elasticsearch.NotFilter{f}
}
// seriesFilter generates a filter that will match against the
// series taken from the URL.
func seriesFilter(value string) elasticsearch.Filter {
return elasticsearch.QueryFilter{
Query: elasticsearch.MatchQuery{
Field: "Series",
Query: value,
Type: "phrase",
},
}
}
// summaryFilter generates a filter that will match against the
// summary field from the charm data.
func summaryFilter(value string) elasticsearch.Filter {
return elasticsearch.QueryFilter{
Query: elasticsearch.MatchQuery{
Field: "CharmMeta.Summary",
Query: value,
Type: "phrase",
},
}
}
// tagsFilter generates a filter that will match against the "tags" field
// in the data. For charms this is the Categories field and for bundles this
// is the Tags field.
func tagsFilter(value string) elasticsearch.Filter {
tags := strings.Split(value, " ")
af := make(elasticsearch.AndFilter, 0, len(tags))
for _, t := range tags {
if t == "" {
continue
}
af = append(af, elasticsearch.OrFilter{
elasticsearch.TermFilter{
Field: "CharmMeta.Categories",
Value: t,
},
elasticsearch.TermFilter{
Field: "CharmMeta.Tags",
Value: t,
},
elasticsearch.TermFilter{
Field: "BundleData.Tags",
Value: t,
},
})
}
return af
}
// termFilter creates a function that generates a filter on the specified
// document field.
func termFilter(field string) func(string) elasticsearch.Filter {
return func(value string) elasticsearch.Filter {
terms := strings.Split(value, " ")
af := make(elasticsearch.AndFilter, 0, len(terms))
for _, t := range terms {
if t == "" {
continue
}
af = append(af, elasticsearch.TermFilter{
Field: field,
Value: t,
})
}
return af
}
}
// bundleFilter is a filter that matches against bundles, based on
// the URL.
var bundleFilter = seriesFilter("bundle")
// typeFilter generates a filter that is used to match either only charms,
// or only bundles.
func typeFilter(value string) elasticsearch.Filter {
if value == "bundle" {
return bundleFilter
}
return elasticsearch.NotFilter{bundleFilter}
}
// sortFields contains a mapping from api fieldnames to the entity fields to search.
var sortESFields = map[string]string{
"name": "Name",
"owner": "User",
"series": "Series",
"downloads": "TotalDownloads",
}
// createSort creates an elasticsearch.Sort query parameter out of a Sort parameter.
func createElasticSort(s SortParam) elasticsearch.Sort {
sort := elasticsearch.Sort{
Field: sortESFields[s.Field],
Order: elasticsearch.Ascending,
}
if s.Descending {
sort.Order = elasticsearch.Descending
}
return sort
}
// searchFields maps the fields that will be requested in the Iter fields
// parameter to the required elasticsearch source filter.
var searchFields = func() map[string]string {
t := reflect.TypeOf(mongodoc.Entity{})
jsonFields := fieldNames(t, "json", nil)
mapping := make(map[string]string, len(jsonFields))
for i, bsonField := range fieldNames(t, "bson", strings.ToLower) {
mapping[bsonField] = jsonFields[i]
}
return mapping
}()
// fieldNames calculates the field names for documents derived from the
// given type. A field name is added to the result for every exported
// field in t. If the field has a tag with the given key then the name be
// the first field in the tags value after it has been comma separated.
// If there is no tag, or the name is empty then the name is derived by
// calling the given function on the field name. If f is nil the field
// name will be used without transformation.
//
// Note: this does not support embedded fields, but we don't have any
// embedded structs in the types we care about yet so that's OK.
func fieldNames(t reflect.Type, key string, f func(string) string) []string {
names := make([]string, 0, t.NumField())
if f == nil {
f = func(s string) string { return s }
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath != "" {
continue
}
parts := strings.Split(field.Tag.Get(key), ",")
if parts[0] != "" {
names = append(names, parts[0])
continue
}
names = append(names, f(field.Name))
}
return names
}