Skip to content

ElasticsearchStorageHandler

redbox.storage.elasticsearch.ElasticsearchStorageHandler

ElasticsearchStorageHandler(es_client, root_index)

Bases: BaseStorageHandler

Storage Handler for Elasticsearch

Initialise the storage handler

PARAMETER DESCRIPTION
es_client

TYPE: Elasticsearch

root_index

TYPE: str

PARAMETER DESCRIPTION
es_client

Elasticsearch client

TYPE: Elasticsearch

root_index

Root index to use. Defaults to "redbox".

TYPE: str

Source code in redbox-core/redbox/storage/elasticsearch.py
53
54
55
56
57
58
59
60
61
62
63
64
65
def __init__(
    self,
    es_client: Elasticsearch,
    root_index: str,
):
    """Initialise the storage handler

    Args:
        es_client (Elasticsearch): Elasticsearch client
        root_index (str, optional): Root index to use. Defaults to "redbox".
    """
    self.es_client = es_client
    self.root_index = root_index

model_type_map class-attribute instance-attribute

model_type_map = {lower(): _rfor v in [Chunk, File]}

es_client instance-attribute

es_client = es_client

root_index instance-attribute

root_index = root_index

get_model_by_model_type

get_model_by_model_type(model_type)
PARAMETER DESCRIPTION
model_type

Source code in redbox-core/redbox/storage/storage_handler.py
17
18
def get_model_by_model_type(self, model_type):
    return self.model_type_map[model_type.lower()]

refresh

refresh(index='*')
PARAMETER DESCRIPTION
index

TYPE: str DEFAULT: '*'

Source code in redbox-core/redbox/storage/elasticsearch.py
67
68
def refresh(self, index: str = "*") -> ObjectApiResponse:
    return self.es_client.indices.refresh(index=f"{self.root_index}-{index}")

write_item

write_item(item)
PARAMETER DESCRIPTION
item

TYPE: PersistableModel

Source code in redbox-core/redbox/storage/elasticsearch.py
70
71
72
73
74
75
76
77
def write_item(self, item: PersistableModel) -> ObjectApiResponse:
    target_index = f"{self.root_index}-{item.model_type.lower()}"

    return self.es_client.index(
        index=target_index,
        id=str(item.uuid),
        body=item.model_dump(mode="json"),
    )

write_items

write_items(items)
PARAMETER DESCRIPTION
items

TYPE: Sequence[PersistableModel]

Source code in redbox-core/redbox/storage/elasticsearch.py
79
80
def write_items(self, items: Sequence[PersistableModel]) -> Sequence[ObjectApiResponse]:
    return list(map(self.write_item, items))

read_item

read_item(item_uuid, model_type)
PARAMETER DESCRIPTION
item_uuid

TYPE: UUID

model_type

TYPE: str

Source code in redbox-core/redbox/storage/elasticsearch.py
82
83
84
85
86
def read_item(self, item_uuid: UUID, model_type: str):
    target_index = f"{self.root_index}-{model_type.lower()}"
    result = self.es_client.get(index=target_index, id=str(item_uuid))
    model = self.get_model_by_model_type(model_type)
    return model(**result.body["_source"])

read_items

read_items(item_uuids, model_type)
PARAMETER DESCRIPTION
item_uuids

TYPE: list[UUID]

model_type

TYPE: str

Source code in redbox-core/redbox/storage/elasticsearch.py
88
89
90
91
92
93
def read_items(self, item_uuids: list[UUID], model_type: str):
    target_index = f"{self.root_index}-{model_type.lower()}"
    result = self.es_client.mget(index=target_index, body={"ids": list(map(str, item_uuids))})

    model = self.get_model_by_model_type(model_type)
    return [model(**item["_source"]) for item in result.body["docs"]]

update_item

update_item(item)
PARAMETER DESCRIPTION
item

TYPE: PersistableModel

Source code in redbox-core/redbox/storage/elasticsearch.py
 95
 96
 97
 98
 99
100
101
102
def update_item(self, item: PersistableModel) -> ObjectApiResponse:
    target_index = f"{self.root_index}-{item.model_type.lower()}"

    return self.es_client.index(
        index=target_index,
        id=str(item.uuid),
        body=item.model_dump(mode="json"),
    )

update_items

update_items(items)
PARAMETER DESCRIPTION
items

TYPE: list[PersistableModel]

Source code in redbox-core/redbox/storage/elasticsearch.py
104
105
def update_items(self, items: list[PersistableModel]) -> list[ObjectApiResponse]:
    return list(map(self.update_item, items))

delete_item

delete_item(item)
PARAMETER DESCRIPTION
item

TYPE: PersistableModel

Source code in redbox-core/redbox/storage/elasticsearch.py
107
108
109
def delete_item(self, item: PersistableModel) -> ObjectApiResponse:
    target_index = f"{self.root_index}-{item.model_type.lower()}"
    return self.es_client.delete(index=target_index, id=str(item.uuid))

delete_items

delete_items(items)
PARAMETER DESCRIPTION
items

TYPE: list[PersistableModel]

Source code in redbox-core/redbox/storage/elasticsearch.py
111
112
113
114
115
116
117
118
119
120
121
122
123
def delete_items(self, items: list[PersistableModel]) -> ObjectApiResponse | None:
    if not items:
        return None

    if len({item.model_type for item in items}) > 1:
        message = "Items with differing model types: {item.model_type for item in items}"
        raise ValueError(message)
    model_type = items[0].model_type
    target_index = f"{self.root_index}-{model_type.lower()}"
    return self.es_client.delete_by_query(
        index=target_index,
        body={"query": {"terms": {"_id": [str(item.uuid) for item in items]}}},
    )

read_all_items

read_all_items(model_type, user_uuid)
PARAMETER DESCRIPTION
model_type

TYPE: str

user_uuid

TYPE: UUID

Source code in redbox-core/redbox/storage/elasticsearch.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def read_all_items(self, model_type: str, user_uuid: UUID) -> list[PersistableModel]:
    target_index = f"{self.root_index}-{model_type.lower()}"
    try:
        result = scan(
            client=self.es_client,
            index=target_index,
            query={
                "query": {
                    "bool": {
                        "should": [
                            {"term": {"creator_user_uuid.keyword": str(user_uuid)}},
                            {"term": {"metadata.creator_user_uuid.keyword": str(user_uuid)}},
                        ]
                    }
                }
            },
            _source=True,
        )

    except NotFoundError:
        log.info("Index %s not found. Returning empty list.", target_index)
        return []

    # Grab the model we'll use to deserialize the items
    model = self.get_model_by_model_type(model_type)
    try:
        results = list(result)
    except NotFoundError:
        return []

    items = []
    for item in results:
        try:
            items.append(model(**item["_source"]))
        except ValidationError as e:
            log.exception("Validation exception for %s", item, exc_info=e)
    return items

list_all_items

list_all_items(model_type, user_uuid)
PARAMETER DESCRIPTION
model_type

TYPE: str

user_uuid

TYPE: UUID

Source code in redbox-core/redbox/storage/elasticsearch.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def list_all_items(self, model_type: str, user_uuid: UUID) -> list[UUID]:
    target_index = f"{self.root_index}-{model_type.lower()}"
    try:
        # Only return _id
        results = scan(
            client=self.es_client,
            index=target_index,
            query={
                "query": {
                    "bool": {
                        "should": [
                            {"term": {"creator_user_uuid.keyword": str(user_uuid)}},
                            {"term": {"metadata.creator_user_uuid.keyword": str(user_uuid)}},
                        ]
                    }
                }
            },
            _source=False,
        )

    except NotFoundError:
        log.info("Index %s not found. Returning empty list.", target_index)
        return []
    return [UUID(item["_id"]) for item in results]

get_file_chunks

get_file_chunks(parent_file_uuid, user_uuid)

get chunks for a given file

PARAMETER DESCRIPTION
parent_file_uuid

TYPE: UUID

user_uuid

TYPE: UUID

Source code in redbox-core/redbox/storage/elasticsearch.py
188
189
190
191
192
193
194
195
196
197
198
199
def get_file_chunks(self, parent_file_uuid: UUID, user_uuid: UUID) -> list[Chunk]:
    """get chunks for a given file"""
    target_index = f"{self.root_index}-chunk"

    return [
        hit_to_chunk(item)
        for item in scan(
            client=self.es_client,
            index=target_index,
            query=build_chunk_query(parent_file_uuid, user_uuid),
        )
    ]

delete_file_chunks

delete_file_chunks(parent_file_uuid, user_uuid)

delete chunks for a given file

PARAMETER DESCRIPTION
parent_file_uuid

TYPE: UUID

user_uuid

TYPE: UUID

Source code in redbox-core/redbox/storage/elasticsearch.py
201
202
203
204
205
206
207
208
def delete_file_chunks(self, parent_file_uuid: UUID, user_uuid: UUID):
    """delete chunks for a given file"""
    target_index = f"{self.root_index}-chunk"

    self.es_client.delete_by_query(
        index=target_index,
        body=build_chunk_query(parent_file_uuid, user_uuid),
    )

get_file_status

get_file_status(file_uuid, user_uuid)

Get the status of a file and associated Chunks

PARAMETER DESCRIPTION
file_uuid

TYPE: UUID

user_uuid

TYPE: UUID

PARAMETER DESCRIPTION
file_uuid

The UUID of the file to get the status of

TYPE: UUID

user_uuid

the UUID of the user

TYPE: UUID

RETURNS DESCRIPTION
FileStatus

The status of the file

TYPE: FileStatus

Source code in redbox-core/redbox/storage/elasticsearch.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def get_file_status(self, file_uuid: UUID, user_uuid: UUID) -> FileStatus:
    """Get the status of a file and associated Chunks

    Args:
        file_uuid (UUID): The UUID of the file to get the status of
        user_uuid (UUID): the UUID of the user

    Returns:
        FileStatus: The status of the file
    """

    # Test 1: Get the file
    try:
        file = self.read_item(file_uuid, "File")
    except NotFoundError as e:
        log.exception("file/%s not found", file_uuid)
        message = f"File {file_uuid} not found"
        raise ValueError(message) from e
    if file.creator_user_uuid != user_uuid:
        log.error("file/%s.%s not owned by %s", file_uuid, file.creator_user_uuid, user_uuid)
        message = f"File {file_uuid} not found"
        raise ValueError(message)

    # Test 2: Get the number of chunks for the file
    chunks = self.get_file_chunks(file_uuid, file.creator_user_uuid)

    if not chunks:
        # File has not been chunked yet
        return FileStatus(
            file_uuid=file_uuid,
            chunk_statuses=[],
            processing_status=ProcessingStatusEnum.embedding,
        )

    # Test 3: Determine the number of embedded chunks for the file
    chunk_statuses = [ChunkStatus(chunk_uuid=chunk.uuid, embedded=bool(chunk.embedding)) for chunk in chunks]

    # Test 4: Determine the latest status
    is_complete = all(chunk_status.embedded for chunk_status in chunk_statuses)

    return FileStatus(
        file_uuid=file_uuid,
        chunk_statuses=chunk_statuses,
        processing_status=ProcessingStatusEnum.complete if is_complete else ProcessingStatusEnum.embedding,
    )