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.

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. "github.com/blevesearch/bleve/index"
  17. "github.com/blevesearch/bleve/mapping"
  18. "github.com/blevesearch/bleve/search"
  19. "github.com/blevesearch/bleve/search/searcher"
  20. )
  21. type FuzzyQuery struct {
  22. Term string `json:"term"`
  23. Prefix int `json:"prefix_length"`
  24. Fuzziness int `json:"fuzziness"`
  25. FieldVal string `json:"field,omitempty"`
  26. BoostVal *Boost `json:"boost,omitempty"`
  27. }
  28. // NewFuzzyQuery creates a new Query which finds
  29. // documents containing terms within a specific
  30. // fuzziness of the specified term.
  31. // The default fuzziness is 1.
  32. //
  33. // The current implementation uses Levenshtein edit
  34. // distance as the fuzziness metric.
  35. func NewFuzzyQuery(term string) *FuzzyQuery {
  36. return &FuzzyQuery{
  37. Term: term,
  38. Fuzziness: 1,
  39. }
  40. }
  41. func (q *FuzzyQuery) SetBoost(b float64) {
  42. boost := Boost(b)
  43. q.BoostVal = &boost
  44. }
  45. func (q *FuzzyQuery) Boost() float64 {
  46. return q.BoostVal.Value()
  47. }
  48. func (q *FuzzyQuery) SetField(f string) {
  49. q.FieldVal = f
  50. }
  51. func (q *FuzzyQuery) Field() string {
  52. return q.FieldVal
  53. }
  54. func (q *FuzzyQuery) SetFuzziness(f int) {
  55. q.Fuzziness = f
  56. }
  57. func (q *FuzzyQuery) SetPrefix(p int) {
  58. q.Prefix = p
  59. }
  60. func (q *FuzzyQuery) Searcher(i index.IndexReader, m mapping.IndexMapping, options search.SearcherOptions) (search.Searcher, error) {
  61. field := q.FieldVal
  62. if q.FieldVal == "" {
  63. field = m.DefaultSearchField()
  64. }
  65. return searcher.NewFuzzySearcher(i, q.Term, q.Prefix, q.Fuzziness, field, q.BoostVal.Value(), options)
  66. }