Mounting module
Pip Install Elasticsearch
Create a connection
From Elasticsearch import Elasticsearch ES = Elasticsearch ([' 192.168.1.1:9200 ']) |
Multi-node
ES = Elasticsearch ([' 192.168.1.1:9200 ', ' 192.168.1.2:9200 ']) |
SSL-enabled connections
ES = Elasticsearch ( [' localhost:443 ', ' other_host:443 '], # Turn on SSL Use_ssl=true, # Make sure we verify SSL certificates (off by default) Verify_certs=true, # provide a path to CA certs on disk ca_certs= '/path/to/ca_certs ' ) |
Create an index
es.Indices.Create(Index=' Test_index ', Ignore= -) Es.indices.delete (index= ' Test_index ', ignore=[400, 404])
|
Ignore can ignore the exception, whose value is the return code of the exception that needs to be ignored, and a common 400 indicates that the index already exists and 404 indicates that the index was not found.
To create an index using a custom map:
mapping = { "Mappings": { "Test_type": { "Properties": { ' Name ': { ' Type ': ' String ', "Index": "Not_analyzed" }, "Phone": { ' Type ': ' String ', "Index": "Not_analyzed" } } } } } Es.indices.create (index= ' Test_index ', ignore=400,body=mapping) |
To view the mapping of an index:
Es.indices.get_mapping ("Test_index") |
Write Data
Insert an article:
Es.index (index= ' Test_index ', doc_type= ' Test_type ', body={"key": "Value"}) |
Bulk write:
Doc = [ {"index": {}}, {' name ': ' Jack ', ' phone ': ' 123456 '}, {"index": {}}, {' name ': ' Joe ', ' phone ': ' 321456 '}, {"index": {}}, {' name ': ' Nicole ', ' phone ': ' 654321 '}, {"index": {}}, {' name ': ' Lucy ', ' phone ': ' 456123 '}, ] Es.bulk (index= ' Test_index ', doc_type= ' Test_type ', Body=doc) |
Delete data
Delete a piece of data by ID
Es.delete (index= "Test_index", doc_type= "Test_type", id= "ZTG5IGMBXTPLS9YLVHBZ") |
Delete data based on query criteria:
BODY = { "Query": { "Match": { "Name": "Joe" } } } Es.delete_by_query (index= ' Test_index ', doc_type= ' Test_type ', body=body) |
Inquire
Querying all data
BODY = { "Query": { "Match_all": {} } } Es.search (index= "Test_index", doc_type= "Test_type", Body=body) |
Or
Es.search (index= "Test_index", doc_type= "Test_type") |
Exactly match term:
#搜索name字段为Nicole的数据 BODY = { "Query": { "term": { "Name": "Nicole" } } } Es.search (index= "Test_index", doc_type= "Test_type", Body=body) |
Keyword matches match:
#搜索name字段包含Nicole关键字的数据 Body = { "query": { "Match": { "name": "Nicole" } } Es.search (index= "Test_index", doc_type= "Test_type", Body=body) |
BOOL Union query,BOOL has 3 Types of query relationships,must ( all satisfied ), should ( One satisfies ), Must_not ( Neither satisfied )
#搜索name为Nicole并且phone为123456的数据 BODY = { "Query": { "BOOL": { "Must": [ { "term": { "Name": "Nicole" } }, { "term": { "Phone": "123456" } } ] } } } Es.search (index= "Test_index", doc_type= "Test_type", Body=body) |
Elasticsearch API Use Method Memo (Python)