1
// Copyright © 2016 Couchbase, Inc.
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
7
// http://www.apache.org/licenses/LICENSE-2.0
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.
21
"github.com/blevesearch/bleve"
22
"github.com/spf13/cobra"
25
var checkFieldName string
28
// checkCmd represents the check command
29
var checkCmd = &cobra.Command{
30
Use: "check [index path]",
31
Short: "checks the contents of the index",
32
Long: `The check command will perform consistency checks on the index.`,
33
RunE: func(cmd *cobra.Command, args []string) error {
35
var fieldNames []string
37
if checkFieldName == "" {
38
fieldNames, err = idx.Fields()
43
fieldNames = []string{checkFieldName}
45
fmt.Printf("checking fields: %v\n", fieldNames)
48
for _, fieldName := range fieldNames {
49
fmt.Printf("checking field: '%s'\n", fieldName)
50
problems, err := checkField(idx, fieldName)
54
totalProblems += problems
57
if totalProblems != 0 {
58
return fmt.Errorf("found %d total problems\n", totalProblems)
65
func checkField(index bleve.Index, fieldName string) (int, error) {
66
termDictionary, err := getDictionary(index, fieldName)
70
fmt.Printf("field contains %d terms\n", len(termDictionary))
74
for term, count := range termDictionary {
75
fmt.Printf("checked %d terms\r", numTested)
76
if checkCount > 0 && numTested >= checkCount {
80
tq := bleve.NewTermQuery(term)
81
tq.SetField(fieldName)
82
req := bleve.NewSearchRequest(tq)
84
res, err := index.Search(req)
89
if res.Total != count {
90
fmt.Printf("unexpected mismatch for term '%s', dictionary %d, search hits %d\n", term, count, res.Total)
96
fmt.Printf("done checking %d terms, found %d problems\n", numTested, numProblems)
98
return numProblems, nil
101
func getDictionary(index bleve.Index, field string) (map[string]uint64, error) {
102
rv := make(map[string]uint64)
103
i, _, err := index.Advanced()
111
d, err := r.FieldDict(field)
117
for err == nil && de != nil {
118
rv[de.Term] = de.Count
128
RootCmd.AddCommand(checkCmd)
129
checkCmd.Flags().StringVarP(&checkFieldName, "field", "f", "", "Restrict check to the specified field name, by default check all fields.")
130
checkCmd.Flags().IntVarP(&checkCount, "count", "c", 100, "Check this many terms, default 100.")