本站源代码
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.

82 lines
2.3KB

  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. "strings"
  17. "github.com/blevesearch/bleve/index"
  18. "github.com/blevesearch/bleve/mapping"
  19. "github.com/blevesearch/bleve/search"
  20. "github.com/blevesearch/bleve/search/searcher"
  21. )
  22. type RegexpQuery struct {
  23. Regexp string `json:"regexp"`
  24. FieldVal string `json:"field,omitempty"`
  25. BoostVal *Boost `json:"boost,omitempty"`
  26. }
  27. // NewRegexpQuery creates a new Query which finds
  28. // documents containing terms that match the
  29. // specified regular expression. The regexp pattern
  30. // SHOULD NOT include ^ or $ modifiers, the search
  31. // will only match entire terms even without them.
  32. func NewRegexpQuery(regexp string) *RegexpQuery {
  33. return &RegexpQuery{
  34. Regexp: regexp,
  35. }
  36. }
  37. func (q *RegexpQuery) SetBoost(b float64) {
  38. boost := Boost(b)
  39. q.BoostVal = &boost
  40. }
  41. func (q *RegexpQuery) Boost() float64 {
  42. return q.BoostVal.Value()
  43. }
  44. func (q *RegexpQuery) SetField(f string) {
  45. q.FieldVal = f
  46. }
  47. func (q *RegexpQuery) Field() string {
  48. return q.FieldVal
  49. }
  50. func (q *RegexpQuery) Searcher(i index.IndexReader, m mapping.IndexMapping, options search.SearcherOptions) (search.Searcher, error) {
  51. field := q.FieldVal
  52. if q.FieldVal == "" {
  53. field = m.DefaultSearchField()
  54. }
  55. // require that pattern NOT be anchored to start and end of term.
  56. // do not attempt to remove trailing $, its presence is not
  57. // known to interfere with LiteralPrefix() the way ^ does
  58. // and removing $ introduces possible ambiguities with escaped \$, \\$, etc
  59. actualRegexp := q.Regexp
  60. if strings.HasPrefix(actualRegexp, "^") {
  61. actualRegexp = actualRegexp[1:] // remove leading ^
  62. }
  63. return searcher.NewRegexpStringSearcher(i, actualRegexp, field,
  64. q.BoostVal.Value(), options)
  65. }
  66. func (q *RegexpQuery) Validate() error {
  67. return nil // real validation delayed until searcher constructor
  68. }
上海开阖软件有限公司 沪ICP备12045867号-1