1// Copyright © 2016 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
15package cmd
16
17import (
18	"encoding/json"
19	"fmt"
20	"io/ioutil"
21
22	"github.com/blevesearch/bleve"
23	"github.com/blevesearch/bleve/mapping"
24	"github.com/spf13/cobra"
25)
26
27var mappingPath, indexType, storeType string
28
29// createCmd represents the create command
30var createCmd = &cobra.Command{
31	Use:   "create [index path]",
32	Short: "creates a new index",
33	Long:  `The create command will create a new empty index.`,
34	Annotations: map[string]string{
35		canMutateBleveIndex: "true",
36	},
37	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
38		// override RootCmd version which opens existing index
39		if len(args) < 1 {
40			return fmt.Errorf("must specify path to index")
41		}
42		return nil
43	},
44	RunE: func(cmd *cobra.Command, args []string) error {
45		var mapping mapping.IndexMapping
46		var err error
47		mapping, err = buildMapping()
48		if err != nil {
49			return fmt.Errorf("error building mapping: %v", err)
50		}
51		idx, err = bleve.NewUsing(args[0], mapping, indexType, storeType, nil)
52		if err != nil {
53			return fmt.Errorf("error creating index: %v", err)
54		}
55		// the inheritted Post action will close the index
56		return nil
57	},
58}
59
60func buildMapping() (mapping.IndexMapping, error) {
61	mapping := mapping.NewIndexMapping()
62	if mappingPath != "" {
63		mappingBytes, err := ioutil.ReadFile(mappingPath)
64		if err != nil {
65			return nil, err
66		}
67		err = json.Unmarshal(mappingBytes, &mapping)
68		if err != nil {
69			return nil, err
70		}
71	}
72	return mapping, nil
73}
74
75func init() {
76	RootCmd.AddCommand(createCmd)
77
78	createCmd.Flags().StringVarP(&mappingPath, "mapping", "m", "", "Path to a file containing a JSON representation of an index mapping to use.")
79	createCmd.Flags().StringVarP(&storeType, "store", "s", bleve.Config.DefaultKVStore, "The bleve storage type to use.")
80	createCmd.Flags().StringVarP(&indexType, "index", "i", bleve.Config.DefaultIndexType, "The bleve index type to use.")
81}
82