一、入门
使用Elasticsearch的第一步是启动Elasticsearch进程,并将API调用发送到它所在的默认端口9200。我们可以通过简单的HTTP GET请求来检索有关我们所创建的节点及其状态的信息:
curl -X GET "localhost:9200/"
在响应中,我们可以看到版本号和集群名称等节点信息。现在我们可以使用类似以下命令来测试集群的运行状态:
curl -XGET 'localhost:9200/_cluster/health?pretty'
该请求返回有关群集状态的信息。您可以在
了解更多信息。
二、索引和搜索
索引和搜索是Elasticsearch API的核心,它们允许您存储和检索大量结构化和非结构化数据。创建索引最简单的方法是使用curl。
curl -X PUT 'localhost:9200/index_name?pretty'
然后您可以通过以下方式将文档添加到索引中:
curl -X PUT 'localhost:9200/index_name/_doc/1?pretty' -d'
{
"title": "Hello World!",
"content": "This is my first Elasticsearch document."
}'
1. 索引API
以下是索引API的示例,其中我们使用html实体化来避免浏览器对html标签的解析。
curl -X PUT 'localhost:9200/<em>my_index</em>&pretty' -H 'Content-Type: application/json' -d'
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
}
}'
2. 搜索API
Elasticsearch提供了各种搜索API,例如match_all、match、term和bool查询等。以下是一个简单的查询示例:
curl -X GET 'localhost:9200/my_index/_search?q=title:Hello&pretty'
三、聚合和过滤
Elasticsearch API还提供了聚合和过滤的功能,可以对搜索结果进行高级操作和计算。以下是一个范围聚合的示例:
curl -X GET 'localhost:9200/my_index/_search?pretty' -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"price_ranges": {
"range": {
"field": "price",
"ranges": [
{
"to": 100
},
{
"from": 100,
"to": 200
},
{
"from": 200
}
]
}
}
}
}'
四、更新和删除
您可以使用以下命令更新文档:
curl -XPOST 'localhost:9200/my_index/_update/1?pretty' -H 'Content-Type: application/json' -d'
{
"doc" : {
"content": "This is my second Elasticsearch document."
}
}'
您可以使用以下命令删除文档:
curl -XDELETE 'localhost:9200/my_index/_doc/1?pretty'
五、总结
Elasticsearch是一个适用于各种应用程序的灵活、可扩展和开源的搜索引擎。它提供了许多高级功能,如搜索、聚合和过滤。在这篇文章中,我们讲解了如何使用API进行索引、搜索、聚合和过滤,以及如何更新和删除文档。希望这篇文章能够为您提供一个良好的入门指南,让您更好地了解Elasticsearch的功能。
原创文章,作者:RRXIV,如若转载,请注明出处:https://www.506064.com/n/361800.html
微信扫一扫
支付宝扫一扫