0、数据结构说明:
book:索引名(相当于数据库)
novel:类型(相当于数据库表)
1、初始化TransportClient
TransportClient client = null;
@Before
public void before() throws Exception {
InetSocketTransportAddress transportAddress =
new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300);
Settings settings = Settings.builder()
.put("cluster.name","wali")
.put("node.name","master")
//自动嗅探整个集群的状态,把集群中其他es节点的ip添加到本地的客户端列表中
.put("client.transport.sniff",true)
.build();
client = new PreBuiltTransportClient(settings);
client.addTransportAddress(transportAddress);
}
@After
public void after() {
if(client != null) {
client.close();
}
}
2、添加单个数据
@Test
public void add() {
Map<String,Object> map = new HashMap<>();
//title数据库表的字段
map.put("title", "标题");
map.put("name", "Tom");
map.put("count", 1000);
map.put("age", 12);
map.put("height",167);
client.prepareIndex("book","novel","1")
.setSource(map).get();
}
3、批量添加数据
@Test
public void addBatch() {
BulkRequestBuilder bulk = client.prepareBulk();
int[] heights = {156,157,158,159,160,161,162,163,167};
int[] counts = {4000,5000,6000,2000,3000,5400,7600,6500,9000};
String[] names = {"Alice","Tom","John","Jack","Bulus","Jamis","Tomas","Jim","Rose"};
int[] ages = {12,13,25,43,65,23,54,47,87};
for(int i = 0; i < 10000; i++ ) {
Map<String,Object> map = new HashMap<>();
map.put("title", "标题" + i);
map.put("name", names[i % 9]);
map.put("count", counts[i % 9]);
map.put("age", ages[i % 9]);
map.put("height", heights[i % 9]);
IndexRequestBuilder add = client.prepareIndex("book","novel",i+"")
.setSource(map);
bulk.add(add);
}
bulk.get();
}
注意:这里批量添加使用BulkRequestBuilder,千万不要在for循环里面用添加单个数据的方式,那样效率非常慢。
3、删除数据
//根据id删除
/*for(int i = 2555 ; i < 2565;i++) {
client.prepareDelete("book", "novel", i+"").get();
}*/
//条件删除
BulkByScrollResponse response =
DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
.filter(QueryBuilders.matchQuery("name", "Tomas"))
.source("book")
.get();
System.out.println(response.getDeleted());//删除文档的数量
4、数据的范围搜索及排序
@Test
public void search() {
SearchRequestBuilder search = client.prepareSearch("book");
search.setTypes("novel");
search.setSearchType(SearchType.QUERY_THEN_FETCH);
search.setFrom(2);
search.setSize(2);
//查询年龄10到40之间,包括10和40
RangeQueryBuilder range = QueryBuilders.rangeQuery("age");
range.from(10);
range.to(40);
search.setQuery(range);
search.addSort("_id", SortOrder.ASC);//_id字段升序返回
SearchResponse response = search.get();
for(SearchHit hit : response.getHits().getHits()) {
System.out.println(hit.getSource() + "---->" + hit.getId());
}
}