/
create.go
81 lines (73 loc) · 2.42 KB
/
create.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
// Copyright © 2016 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/blevesearch/bleve"
"github.com/blevesearch/bleve/mapping"
"github.com/spf13/cobra"
)
var mappingPath, indexType, storeType string
// createCmd represents the create command
var createCmd = &cobra.Command{
Use: "create [index path]",
Short: "creates a new index",
Long: `The create command will create a new empty index.`,
Annotations: map[string]string{
canMutateBleveIndex: "true",
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// override RootCmd version which opens existing index
if len(args) < 1 {
return fmt.Errorf("must specify path to index")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
var mapping mapping.IndexMapping
var err error
mapping, err = buildMapping()
if err != nil {
return fmt.Errorf("error building mapping: %v", err)
}
idx, err = bleve.NewUsing(args[0], mapping, indexType, storeType, nil)
if err != nil {
return fmt.Errorf("error creating index: %v", err)
}
// the inheritted Post action will close the index
return nil
},
}
func buildMapping() (mapping.IndexMapping, error) {
mapping := mapping.NewIndexMapping()
if mappingPath != "" {
mappingBytes, err := ioutil.ReadFile(mappingPath)
if err != nil {
return nil, err
}
err = json.Unmarshal(mappingBytes, &mapping)
if err != nil {
return nil, err
}
}
return mapping, nil
}
func init() {
RootCmd.AddCommand(createCmd)
createCmd.Flags().StringVarP(&mappingPath, "mapping", "m", "", "Path to a file containing a JSON representation of an index mapping to use.")
createCmd.Flags().StringVarP(&storeType, "store", "s", bleve.Config.DefaultKVStore, "The bleve storage type to use.")
createCmd.Flags().StringVarP(&indexType, "index", "i", bleve.Config.DefaultIndexType, "The bleve index type to use.")
}