首先,确保您的系统已安装Java 8或更高版本,因为Elasticsearch需要Java运行环境。
- 从 Elasticsearch官网 下载适合Windows的ZIP包。
- 解压ZIP文件。
- 运行
bin\elasticsearch.bat
。
brew tap elastic/tap
brew install elastic/tap/elasticsearch-full
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
sudo apt-get install apt-transport-https
sudo sh -c 'echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" > /etc/apt/sources.list.d/elastic-7.x.list'
sudo apt-get update && sudo apt-get install elasticsearch
bin\elasticsearch
sudo service elasticsearch start
Elasticsearch主要使用RESTful API,您可以使用如curl
的工具进行交互。
curl -X PUT "localhost:9200/my_index"
curl -X POST "localhost:9200/my_index/_doc/" -H 'Content-Type: application/json' -d'
{
"name": "John Doe",
"age": 30
}'
-
使用URI搜索:
curl -X GET "localhost:9200/my_index/_search?q=name:John"
-
使用请求体搜索:
curl -X GET "localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d' { "query": { "match": { "name": "John" } } }'
-
组合查询:
curl -X GET "localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d' { "query": { "bool": { "must": [ { "match": { "name": "John" } }, { "range": { "age": { "gte": 25 } } } ] } } }'
-
更新文档:
curl -X POST "localhost:9200/my_index/_update/document_id" -H 'Content-Type: application/json' -d' { "doc": { "age": 31 } }'
-
删除文档:
curl -X DELETE "localhost:9200/my_index/_doc/document_id"
curl -X DELETE "localhost:9200/my_index"
首先,您需要安装Python Elasticsearch客户端库。您可以使用pip进行安装:
pip install elasticsearch
使用Elasticsearch客户端,首先需要建立连接:
from elasticsearch import Elasticsearch
# 默认连接localhost:9200
es = Elasticsearch()
# 或指定主机和端口
es = Elasticsearch(hosts=["http://your_host:your_port"])
-
创建索引:
es.indices.create(index="my_index", ignore=400)
-
索引文档:
doc_data = { "name": "John Doe", "age": 30 } response = es.index(index="my_index", doc_type="_doc", body=doc_data)
-
检索文档:
response = es.search(index="my_index", body={ "query": { "match": { "name": "John" } } })
-
更新文档:
update_data = { "doc": { "age": 31 } } response = es.update(index="my_index", doc_type="_doc", id=document_id, body=update_data)
-
删除文档:
response = es.delete(index="my_index", doc_type="_doc", id=document_id)
-
删除索引:
es.indices.delete(index="my_index", ignore=[400, 404])
这只是一个入门级的Elasticsearch教程。为了深入了解其功能,请参阅 Elasticsearch官方文档 和 Python客户端官方文档。