Elasticsearch API简单操作
在操作Elasticsearch之前,需要先安装Elasticsearch集群,安装博客如:Elasticsearch集群安装
下面介绍简单介绍Elasticsearch的3中操作方式,分别curl,java,python操作。
1.curl操作
基本上curl操作,通过GET,POST,DELETE操作就OK
具体的模式如下:
curl -X<VERB> '<PROTOCOL>://<HOST>:<PORT>/<PATH>?<QUERY_STRING>' -d '<BODY>'
POST操作(PUT操作类似)
# 这里的people表示index,sanguo表示type,1表示id
curl -H 'Content-Type:application/json' -XPOST 'http://localhost:9200/people/sanguo/1' -d '{"name":"caocao","age":32,"sex":"male"}'
curl -H 'Content-Type:application/json' -XPOST 'http://localhost:9200/people/sanguo/2' -d '{"name":"liubei","age":30,"sex":"male"}'
curl -H 'Content-Type:application/json' -XPOST 'http://localhost:9200/people/sanguo/3' -d '{"name":"guanyu","age":28,"sex":"male"}'
curl -H 'Content-Type:application/json' -XPOST 'http://localhost:9200/people/sanguo/4' -d '{"name":"zhangfei","age":27,"sex":"male"}'
curl -H 'Content-Type:application/json' -XPOST 'http://localhost:9200/people/sanguo/5' -d '{"name":"sunquan","age":25,"sex":"male"}'
curl -H 'Content-Type:application/json' -XPOST 'http://localhost:9200/people/sanguo/6' -d '{"name":"zhouyu","age":30,"sex":"male"}'
curl -H 'Content-Type:application/json' -XPOST 'http://localhost:9200/people/sanguo/7' -d '{"name":"xiaoqiao","age":24,"sex":"female"}'
GET操作
# 查找index为people,type为sanguo,id为1的数据
curl -H 'content-type:application/json' -XGET 'http://localhost:9200/people/sanguo/1'
# 查找所有的数据
curl -H 'content-type:application/json' -XGET 'http://localhost:9200/_search' -d '
{
"query": {
"match_all": {}
}
}'
# 全部扫描,查找name字段为caocao的数据
curl -H 'content-type:application/json' -XGET 'http://localhost:9200/_search?q=name:caocao'
# 全部扫描,查找name字段为caocao的数据
curl -H 'content-type:application/json' -XGET 'http://localhost:9200/_search' -d '{"query": {"match": {"name":"caocao"}}}'
2.Java api操作
pom.xml文件依赖
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.5.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.5.2</version>
</dependency>
</dependencies>
java代码
package com.test;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class ESDemo {
public static void main(String[] args) throws UnknownHostException, ExecutionException, InterruptedException {
Settings settings = Settings.builder()
.put("cluster.name", "my-application")
.put("client.transport.sniff", true)
.build();
// 获取client的客户端对象
TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
new TransportAddress(InetAddress.getByName("localhost"), 9300));
// insertId(client);
// updateId(client);
getId(client);
getId2(client);
searchAll(client);
searchMatch(client, "30");
searchMatch(client, "xiaoqiao");
searchBoolMatch(client);
searchFilterMatch(client);
client.close();
}
// 更新操作
private static void updateId(TransportClient client) {
Map source = new HashMap<String, Object>();
source.put("name", "zhugeliang");
source.put("age", 26);
source.put("sex", "male");
UpdateResponse response = client.prepareUpdate("people", "sanguo", "8").setDoc(source).execute().actionGet();
DocWriteResponse.Result result = response.getResult();
System.out.println(result);
}
// 过滤及范围查询
private static void searchFilterMatch(TransportClient client) {
QueryBuilder q = QueryBuilders.rangeQuery("age").gte("25").lt("32");
SearchResponse response = client.prepareSearch("people")
.setQuery(q)
.setFrom(0) //从第一个开始
.setSize(5) // 取5个数据
.addSort("age", SortOrder.DESC) // 排序规则
.execute()
.actionGet();
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
System.out.println("--------------------------------");
}
// 匹配查询,根据条件匹配查询
private static void searchBoolMatch(TransportClient client) {
QueryBuilder q = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("name", "caocao"))
.must(QueryBuilders.matchQuery("age", "32"));
SearchResponse response = client.prepareSearch("people").setQuery(q).execute().actionGet();
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
System.out.println("--------------------------------");
}
// 全部扫描
private static void searchMatch(TransportClient client, String query) {
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(query);
SearchResponse response = client.prepareSearch("people").setQuery(queryBuilder).execute().actionGet();
SearchHits hits = response.getHits();
SearchHit[] hitsHits = hits.getHits();
for (SearchHit hit : hitsHits) {
System.out.println(hit.getSourceAsString());
}
System.out.println("--------------------------------");
}
// 通过id查找
private static void getId(TransportClient client) throws ExecutionException, InterruptedException {
// get index/type/id
GetResponse getResponse = client.prepareGet("people", "sanguo", "1").execute().get();
Map<String, Object> source1 = getResponse.getSource();
System.out.println(source1);
System.out.println("--------------------------------");
}
// 通过id查找
private static void getId2(TransportClient client) throws ExecutionException, InterruptedException {
// get 另外一种形式
String source = client.prepareGet().setIndex("people").setType("sanguo").setId("3").execute().actionGet().getSourceAsString();
System.out.println(source);
System.out.println("--------------------------------");
}
// 扫描所有的数据
private static void searchAll(TransportClient client) {
// search 搜索
SearchHits search = client.prepareSearch().execute().actionGet().getHits();
SearchHit[] hits = search.getHits();
for (SearchHit hit : hits) {
String string = hit.getSourceAsString();
System.out.println(string);
}
System.out.println("--------------------------------");
}
// 插入一条数据
private static void insertId(TransportClient client) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", "zhugeliang");
map.put("age", "26");
map.put("sex", "male");
IndexResponse response = client.prepareIndex().setIndex("people").setType("sanguo").setId("8").setSource(map).execute().actionGet();
DocWriteResponse.Result result = response.getResult();
System.out.println(result);
System.out.println("--------------------------------");
}
}
3.python api 操作
pip安装elasticsearch
pip install elasticsearch
python操作代码
python api比较简单,因为返回的是一个Doc文档,是dict类型,我们只需要对从dict中获取数据就好。
from elasticsearch import Elasticsearch
if __name__ == '__main__':
es = Elasticsearch(hosts="localhost")
res = es.get("people", "sanguo", "1")
print(res)
print("---" * 20)
res2 = es.search(index='people')
print(type(res2))
for i in res2["hits"]["hits"]:
print(i["_source"])
print("---" * 20)
res3 = es.search(index="people", body={"query": {"match": {"name": "caocao"}}})
for i in res3["hits"]["hits"]:
print(i["_source"])
print("---" * 20)
# res4 = es.index(index="people", doc_type="sanguo", id="9", body={"name": "lubu", "age": 30, "sex": "male"})
# print(res4)
# res5 = es.delete(index="people", doc_type="sanguo", id="9")
# print(res5)
res6 = es.index(index="people", doc_type="sanguo", id="9",
body={"name": "sunshangxiang", "age": 25, "sex": "female"})
print(res6)
print("---" * 20)