Elasticsearch Client
Install elasticsearch
pip install elasticsearch
Connection Elasticsearch
from elasticsearch import Elasticsearch
client = Elasticsearch('http://localhost:9200')
client.ping()
Insert one row
client.index(index = 'student', id = 6, body = {'fullname': 'Hai Hùng SG', 'score': 8.3})
Select One
client.get(index = 'student', id = 6)
Insert Bulk
client.bulk(index = 'student', body=[
{ "index": { "_id": 7 } },
{ "fullname": 'Đinh Hoa Lư', "score": 7.6 },
{ "index": { "_id": 8 } },
{ "fullname": 'Cao Hoàng', "score": 6.8 },
])
Select All Row
client.search(index='student', body = {
"query": {
"match_all": {}
}
})
Count
client.count(index='category')
Create Index
client.indices.create(index='example', mappings = {
'properties': {
'name': {
'type': 'text'
},
'vec': {
'type': 'dense_vector',
'dims': 3,
'similarity': 'l2_norm'
}
}
})
Bulk Insert
client.bulk(index = 'example', body=[
{"index": {"_id": 1}},
{"name": "laptop", "vec": [3, 2, 5]},
{"index": {"_id": 2}},
{"name": "mouse", "vec": [1, 3, 4]},
{"index": {"_id": 3}},
{"name": "keyboard", "vec": [6, 7, 3]}
])
Search Vector
client.search(index='example', body ={
"knn": {
"field": "vec",
"query_vector": [2, 8, 4],
"k": 2,
"num_candidates": 3
}
}, filter_path='hits.hits')