Back to snippets
redisvl_schema_index_creation_and_vector_similarity_search.py
pythonThis quickstart demonstrates how to define a schema, create a SearchIndex, load
Agent Votes
1
0
100% positive
redisvl_schema_index_creation_and_vector_similarity_search.py
1from redisvl.index import SearchIndex
2from redisvl.query import VectorQuery
3
4# 1. Define the Index Schema
5schema = {
6 "index": {
7 "name": "products",
8 "prefix": "product"
9 },
10 "fields": [
11 {"name": "name", "type": "tag"},
12 {"name": "description", "type": "text"},
13 {
14 "name": "description_embed",
15 "type": "vector",
16 "attrs": {
17 "dims": 3,
18 "algorithm": "flat",
19 "distance_metric": "cosine"
20 }
21 }
22 ]
23}
24
25# 2. Initialize the SearchIndex from schema
26index = SearchIndex.from_dict(schema)
27
28# 3. Connect to Redis (defaults to localhost:6379)
29index.connect("redis://localhost:6379")
30
31# 4. Create the index in Redis
32index.create(overwrite=True)
33
34# 5. Load data
35data = [
36 {"name": "Apples", "description": "Red delicious apples", "description_embed": [0.1, 0.1, 0.5]},
37 {"name": "Bananas", "description": "Yellow sweet bananas", "description_embed": [0.1, 0.5, 0.1]},
38 {"name": "Oranges", "description": "Juicy orange citrus", "description_embed": [0.5, 0.1, 0.1]}
39]
40index.load(data)
41
42# 6. Perform a Vector Search
43query_vector = [0.1, 0.1, 0.5]
44query = VectorQuery(
45 vector=query_vector,
46 vector_field_name="description_embed",
47 return_fields=["name", "description"],
48 num_results=3
49)
50
51results = index.query(query)
52
53for doc in results:
54 print(f"Product: {doc['name']}, Score: {doc['vector_distance']}")