You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

phrase.go 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (c) 2014 Couchbase, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package query
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/blevesearch/bleve/index"
  19. "github.com/blevesearch/bleve/mapping"
  20. "github.com/blevesearch/bleve/search"
  21. "github.com/blevesearch/bleve/search/searcher"
  22. )
  23. type PhraseQuery struct {
  24. Terms []string `json:"terms"`
  25. Field string `json:"field,omitempty"`
  26. BoostVal *Boost `json:"boost,omitempty"`
  27. }
  28. // NewPhraseQuery creates a new Query for finding
  29. // exact term phrases in the index.
  30. // The provided terms must exist in the correct
  31. // order, at the correct index offsets, in the
  32. // specified field. Queried field must have been indexed with
  33. // IncludeTermVectors set to true.
  34. func NewPhraseQuery(terms []string, field string) *PhraseQuery {
  35. return &PhraseQuery{
  36. Terms: terms,
  37. Field: field,
  38. }
  39. }
  40. func (q *PhraseQuery) SetBoost(b float64) {
  41. boost := Boost(b)
  42. q.BoostVal = &boost
  43. }
  44. func (q *PhraseQuery) Boost() float64 {
  45. return q.BoostVal.Value()
  46. }
  47. func (q *PhraseQuery) Searcher(i index.IndexReader, m mapping.IndexMapping, options search.SearcherOptions) (search.Searcher, error) {
  48. return searcher.NewPhraseSearcher(i, q.Terms, q.Field, options)
  49. }
  50. func (q *PhraseQuery) Validate() error {
  51. if len(q.Terms) < 1 {
  52. return fmt.Errorf("phrase query must contain at least one term")
  53. }
  54. return nil
  55. }
  56. func (q *PhraseQuery) UnmarshalJSON(data []byte) error {
  57. type _phraseQuery PhraseQuery
  58. tmp := _phraseQuery{}
  59. err := json.Unmarshal(data, &tmp)
  60. if err != nil {
  61. return err
  62. }
  63. q.Terms = tmp.Terms
  64. q.Field = tmp.Field
  65. q.BoostVal = tmp.BoostVal
  66. return nil
  67. }