|
1 |
| -# Multi-Category Filters |
| 1 | +# Multi-Category/Tag Filters |
2 | 2 |
|
3 |
| -Sometimes you may want to filter documents in Chroma based on multiple categories e.g. `games` and `movies`. |
| 3 | +Sometimes you may want to filter documents in Chroma based on multiple categories or tags e.g. `games` and `movies`. |
4 | 4 | Unfortunately, Chroma does not yet support complex data-types like lists or sets so that one can use a single metadata
|
5 | 5 | field to store and filter by. It is also not possible to use fuzzy search `LIKE` queries on metadata fields.
|
6 | 6 |
|
7 | 7 | To solve this problem without introducing a complex logic on the client side, we suggest the following approach.
|
8 | 8 |
|
9 | 9 | When adding document to a collection add each category it belongs to as a boolean metadata field:
|
10 | 10 |
|
11 |
| -!!! note "No Empty Categories" |
| 11 | +!!! note "No Empty Categories/Tags" |
12 | 12 |
|
13 | 13 | Only add categories an item belongs to with flags set to `True`.
|
14 | 14 | Do not add categories an item does not belong to and set the flag to `False`.
|
15 | 15 |
|
16 | 16 | ```python
|
17 |
| -import uuid |
18 | 17 |
|
19 |
| -collection.add(ids=[f"{uuid.uuid4()}"], documents=["This is a document"], metadatas=[{"games": True, "movies": True}]) |
| 18 | +collection.add( |
| 19 | + ids=[f"{uuid.uuid4()}"], |
| 20 | + documents=["This is a document"], |
| 21 | + metadatas=[{"games": True, "movies": True}], |
| 22 | +) |
20 | 23 | ```
|
21 | 24 |
|
22 | 25 | When querying documents, you can filter by multiple categories by using the `where` parameter:
|
23 | 26 |
|
24 | 27 | ```python
|
25 |
| -results = collection.query(query_texts=["This is a query document"], where={"games": True, "movies": True}) |
| 28 | +results = collection.query( |
| 29 | + query_texts=["This is a query document"], |
| 30 | + where={"games": True}, |
| 31 | +) |
| 32 | +# or a more complex query |
| 33 | +results = collection.query( |
| 34 | + query_texts=["This is a query document"], |
| 35 | + where={"$or": [{"games": True}, {"movies": True}]}, |
| 36 | +) |
26 | 37 | ```
|
27 |
| - |
|
0 commit comments