通常通过HTTP REST API访问Elasticsearch。通常使用cURL库。搜索服务器和客户端(您或您的应用程序)之间的消息以JSON字符串的形式发送。默认情况下,Elasticsearch在端口9200上运行。
在下面的示例中,添加了 ?pretty 用于告诉Elasticsearch修饰JSON响应的功能。在应用程序中使用这些端点时,无需添加此查询参数。
如果我们打算以后更新索引中的信息,则最好为索引的文档分配唯一的ID。要将文档添加到名为的索引中megacorp,其类型employee和ID为1:
curl -XPUT "http://localhost:9200/megacorp/employee/1?pretty" -d' { "first_name" : "John", "last_name" : "Smith", "age" : 25, "about" : "I love to go rock climbing", "interests": [ "sports", "music" ] }'
响应:
{ "_index": "megacorp", "_type": "employee", "_id": "1", "_version": 1, "_shards": { "total": 2, "successful": 1, "failed": 0 }, "created": true }
如果在我们发送PUT调用时不存在该索引,则会创建该索引。
POST /megacorp/employee?pretty { "first_name" : "Jane", "last_name" : "Smith", "age" : 32, "about" : "I like to collect rock albums", "interests": [ "music" ] }
响应:
{ "_index": "megacorp", "_type": "employee", "_id": "AVYg2mBJYy9ijdngfeGa", "_version": 1, "_shards": { "total": 2, "successful": 2, "failed": 0 }, "created": true }
curl -XGET "http://localhost:9200/megacorp/employee/1?pretty"
响应:
{ "_index": "megacorp", "_type": "employee", "_id": "1", "_version": 1, "found": true, "_source": { "first_name": "John", "last_name": "Smith", "age": 25, "about": "I love to go rock climbing", "interests": [ "sports", "music" ] } }
从megacorp索引中获取10个文档,其类型为employee:
curl -XGET "http://localhost:9200/megacorp/employee/_search?pretty"
响应:
{ "took": 2, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 2, "max_score": 1, "hits": [ { "_index": "megacorp", "_type": "employee", "_id": "1", "_score": 1, "_source": { "first_name": "John", "last_name": "Smith", "age": 25, "about": "I love to go rock climbing", "interests": [ "sports", "music" ] } }, { "_index": "megacorp", "_type": "employee", "_id": "AVYg2mBJYy9ijdngfeGa", "_score": 1, "_source": { "first_name": "Jane", "last_name": "Smith", "age": 32, "about": "I like to collect rock albums", "interests": [ "music" ] } } ] } }
使用match查询进行简单搜索,该查询在提供的字段中查找完全匹配:
curl -XGET "http://localhost:9200/megacorp/employee/_search" -d' { "query" : { "match" : { "last_name" : "Smith" } } }'
响应:
{ "took": 2, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 1, "max_score": 0.6931472, "hits": [ { "_index": "megacorp", "_type": "employee", "_id": "1", "_score": 0.6931472, "_source": { "first_name": "John", "last_name": "Smith", "age": 25, "about": "I love to go rock climbing", "interests": [ "sports", "music" ] } } ] } }