• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

georgia-tech-db / eva / #754

04 Sep 2023 09:54PM UTC coverage: 74.807% (-5.5%) from 80.336%
#754

push

circle-ci

jiashenC
update case

8727 of 11666 relevant lines covered (74.81%)

0.75 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

33.96
/evadb/executor/create_index_executor.py
1
# coding=utf-8
2
# Copyright 2018-2023 EvaDB
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
from pathlib import Path
1✔
16

17
import pandas as pd
1✔
18

19
from evadb.catalog.sql_config import IDENTIFIER_COLUMN
1✔
20
from evadb.database import EvaDBDatabase
1✔
21
from evadb.executor.abstract_executor import AbstractExecutor
1✔
22
from evadb.executor.executor_utils import ExecutorError, handle_vector_store_params
1✔
23
from evadb.models.storage.batch import Batch
1✔
24
from evadb.plan_nodes.create_index_plan import CreateIndexPlan
1✔
25
from evadb.storage.storage_engine import StorageEngine
1✔
26
from evadb.third_party.vector_stores.types import FeaturePayload
1✔
27
from evadb.third_party.vector_stores.utils import VectorStoreFactory
1✔
28
from evadb.utils.logging_manager import logger
1✔
29

30

31
class CreateIndexExecutor(AbstractExecutor):
1✔
32
    def __init__(self, db: EvaDBDatabase, node: CreateIndexPlan):
1✔
33
        super().__init__(db, node)
1✔
34

35
    def exec(self, *args, **kwargs):
1✔
36
        if self.catalog().get_index_catalog_entry_by_name(self.node.name):
×
37
            msg = f"Index {self.node.name} already exists."
×
38
            logger.error(msg)
×
39
            raise ExecutorError(msg)
40

41
        self.index_path = self._get_index_save_path()
×
42
        self.index = None
×
43
        self._create_index()
×
44

45
        yield Batch(
×
46
            pd.DataFrame(
47
                [f"Index {self.node.name} successfully added to the database."]
48
            )
49
        )
50

51
    def _get_index_save_path(self) -> Path:
1✔
52
        index_dir = Path(self.config.get_value("storage", "index_dir"))
×
53
        if not index_dir.exists():
×
54
            index_dir.mkdir(parents=True, exist_ok=True)
×
55
        return str(
×
56
            index_dir
57
            / Path("{}_{}.index".format(self.node.vector_store_type, self.node.name))
58
        )
59

60
    def _create_index(self):
1✔
61
        try:
×
62
            # Get feature tables.
63
            feat_catalog_entry = self.node.table_ref.table.table_obj
×
64

65
            # Get feature column.
66
            feat_col_name = self.node.col_list[0].name
×
67
            feat_column = [
×
68
                col for col in feat_catalog_entry.columns if col.name == feat_col_name
69
            ][0]
70

71
            # Add features to index.
72
            # TODO: batch size is hardcoded for now.
73
            input_dim = -1
×
74
            storage_engine = StorageEngine.factory(self.db, feat_catalog_entry)
×
75
            for input_batch in storage_engine.read(feat_catalog_entry):
×
76
                if self.node.function:
×
77
                    # Create index through function expression.
78
                    # Function(input column) -> 2 dimension feature vector.
79
                    input_batch.modify_column_alias(feat_catalog_entry.name.lower())
×
80
                    feat_batch = self.node.function.evaluate(input_batch)
×
81
                    feat_batch.drop_column_alias()
×
82
                    input_batch.drop_column_alias()
×
83
                    feat = feat_batch.column_as_numpy_array("features")
×
84
                else:
85
                    # Create index on the feature table directly.
86
                    # Pandas wraps numpy array as an object inside a numpy
87
                    # array. Use zero index to get the actual numpy array.
88
                    feat = input_batch.column_as_numpy_array(feat_col_name)
×
89

90
                row_id = input_batch.column_as_numpy_array(IDENTIFIER_COLUMN)
×
91

92
                for i in range(len(input_batch)):
×
93
                    row_feat = feat[i].reshape(1, -1)
×
94
                    if self.index is None:
×
95
                        input_dim = row_feat.shape[1]
×
96
                        self.index = VectorStoreFactory.init_vector_store(
×
97
                            self.node.vector_store_type,
98
                            self.node.name,
99
                            **handle_vector_store_params(
100
                                self.node.vector_store_type, self.index_path
101
                            ),
102
                        )
103
                        self.index.create(input_dim)
×
104

105
                    # Row ID for mapping back to the row.
106
                    self.index.add([FeaturePayload(row_id[i], row_feat)])
×
107

108
            # Persist index.
109
            self.index.persist()
×
110

111
            # Save to catalog.
112
            self.catalog().insert_index_catalog_entry(
×
113
                self.node.name,
114
                self.index_path,
115
                self.node.vector_store_type,
116
                feat_column,
117
                self.node.function.signature() if self.node.function else None,
118
            )
119
        except Exception as e:
120
            # Delete index.
121
            if self.index:
122
                self.index.delete()
123

124
            # Throw exception back to user.
125
            raise ExecutorError(str(e))
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc