datadabllp

Elasticsearch for vector search

Jul 8th, 2024
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. from elasticsearch import Elasticsearch
  2. import numpy as np
  3.  
  4. # Connect to Elasticsearch
  5. es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
  6.  
  7. # Index a document with its vector embedding
  8. doc = {
  9.     'text': 'The new EU AI regulations focus on transparency and accountability.',
  10.     'vector': np.random.rand(384).tolist()  # Simulated 384-dimensional embedding
  11. }
  12. es.index(index='documents', body=doc)
  13.  
  14. # Perform a vector similarity search
  15. query_vector = np.random.rand(384).tolist()  # Simulated query embedding
  16. search_body = {
  17.     "query": {
  18.         "script_score": {
  19.             "query": {"match_all": {}},
  20.             "script": {
  21.                 "source": "cosineSimilarity(params.query_vector, 'vector') + 1.0",
  22.                 "params": {"query_vector": query_vector}
  23.             }
  24.         }
  25.     }
  26. }
  27. results = es.search(index='documents', body=search_body)
  28.  
Advertisement
Add Comment
Please, Sign In to add comment