好程序员Java学习路线分享创建Java class,首先通过Transport Client获取ES的连接
private Client client;
//通过Transport Client获取ES的连接
@Before
public void getClient() throws Exception{
????//ES服务的JavaAPI的port为9300
????//注意:如果请求一个ES集群,可以多添几个节点
????//为了避免在一个节点出现网络问题导致的请求失败问题,可以自动切换另外一个节点
????client = TransportClient.builder().build()
????????????.addTransportAddress(new InetSocketTransportAddress(
????????????????????InetAddress.getByName("localhost"),9300));
????????????//.addTransportAddress(...);
}
操作命令
----------------------------------------新建文档------------------------------------
- 使用json来创建文档(插入一条数据),自动创建索引和映射
@Test
public void createDocument1(){
????// json格式的数据
????//json "需要转义 -> \
????String source = "{" +
????????????"\"id\":\"1\"," +
????????????"\"title\":\"Lucene是一套用于全文检索和搜寻的开源程式库\"," +
????????????"\"content\":\"Lucene提供了一个简单却强大的应用程式接口,能够做全文索引和搜寻\"" +
????????????"}";
????//创建文档, 定义索引名称,文档类型,主键唯一标识ID
????//execute().actionGet() == get() ?代表立刻执行
????IndexResponse indexResponse =
????????????client.prepareIndex("blog", "article", "1")
????????????????????.setSource(source).get(); //加载数据并触发
????this.getResponse(indexResponse); ?//对应下面封装信息
????client.close();
}
将打印信息封装成类,方便this调用
//获取响应信息
private void getResponse(IndexResponse indexResponse) {
????System.out.println("索引名称: " + indexResponse.getIndex());
????System.out.println("文档类型: "+indexResponse.getType());
????System.out.println("ID: "+indexResponse.getId());
????System.out.println("版本: "+indexResponse.getVersion());
????System.out.println("是否创建成功: "+indexResponse.isCreated());
}
- 使用map创建文档,自动创建索引和映射
@Test
public void createDocument2(){
????// map类型的数据
????Map<String,Object> source = new HashMap<>();
????source.put("id","2");
????source.put("title","ElasticSearch");
????source.put("content","是一个分布式的 RESTful 风格的搜索和数据分析引擎");
????//创建文档
????IndexResponse indexResponse = client.prepareIndex("blog", "article", "2")
????????????.setSource(source).get();
????this.getResponse(indexResponse);
????client.close();
}
使用ES帮助类(执行类),创建文档
@Test
public void createDocument3() throws Exception{
????XContentBuilder source = XContentFactory.jsonBuilder()
????????????.startObject() //封装数据
????????????????.field("id","3")
????????????????.field("title","ES的核心")
????????????????.field("content","集中的是巴拉巴拉")
????????????.endObject();
????System.out.println(source.toString());
????//创建文档
????IndexResponse indexResponse = client.prepareIndex("blog", "article", "3")
????????????.setSource(source).get();
????this.getResponse(indexResponse);
????client.close();
}
----------------------------------------搜索文档------------------------------------
输出格式为json格式
搜索文档数据 -- 单个索引 ?prepareGet
@Test
public void testGetData1(){
????GetResponse getResponse = client.prepareGet("blog", "article", "1").get();
????System.out.println(getResponse.getSourceAsString());
????client.close(); ??//输出格式为json格式
}
搜索文档数据 -- 多个索引 ?prepareMultiGet
@Test
public void testGetData2(){
????MultiGetResponse multiGetResponse = client.prepareMultiGet()
????????????.add("blog", "article", "1")
????????????.add("blog", "article", "2", "3")
????????????.get();
????for (MultiGetItemResponse itemResponse : multiGetResponse){
????????GetResponse response = itemResponse.getResponse();
????????if (response.isExists()){
????????????System.out.println(response.getSourceAsString());
????????}
????}
????client.close();
}
----------------------------------------更新文档------------------------------------
doc更新
创建更新对象
@Test
public void testUpdate1() throws Exception{
????UpdateRequest request = new UpdateRequest();
????request.index("blog");
????request.type("article");
????request.id("1");
????request.doc(XContentFactory.jsonBuilder() //doc 更新方法
????.startObject()
????????????.field("id","1")
????????????.field("title","更新:1")
????????????.field("content","更新:1")
????.endObject());
????UpdateResponse updateResponse = client.update(request).get();
????System.out.println("索引名称: " + updateResponse.getIndex());
????System.out.println("文档类型: "+updateResponse.getType());
????System.out.println("ID: "+updateResponse.getId());
????System.out.println("版本: "+updateResponse.getVersion());
????System.out.println("是否创建成功: "+updateResponse.isCreated()); //false
????client.close();
}
直接调用client.update
@Test
public void testUpdate2() throws Exception{
????UpdateResponse updateResponse =
????????????client.update(new UpdateRequest("blog", "article", "2")
????????????????????.doc(XContentFactory.jsonBuilder() //doc 更新方法
????????????????????????.startObject()
????????????????????????????.field("id", "2")
????????????????????????????.field("title", "更新:2")
????????????????????????????.field("content", "更新:2")
????????????????????????.endObject()))
????????????????????.get();
????System.out.println("索引名称: " + updateResponse.getIndex());
????System.out.println("文档类型: "+updateResponse.getType());
????System.out.println("ID: "+updateResponse.getId());
????System.out.println("版本: "+updateResponse.getVersion());
????System.out.println("是否创建成功: "+updateResponse.isCreated()); //false
????client.close();
}
创建并更新
@Test
public void testUpdate3() throws Exception{
????// 设置一个查询的条件,使用ID查询,如果查不到数据,则添加IndexRequest的文档数据
????IndexRequest indexRequest = new IndexRequest("blog1", "article", "4")
????????????.source(XContentFactory.jsonBuilder()
????????????????.startObject()
????????????????????.field("id", "4")
????????????????????.field("title", "李雪静加油")
????????????????????.field("content", "Fighting!")
????????????????.endObject());
????//设置更新的数据,使用ID查询,如果能查到,则更新UpdateRequest的数据
????UpdateRequest updateRequest = new UpdateRequest("blog1", "article", "4")
????????????.doc(XContentFactory.jsonBuilder()
????????????????????.startObject()
????????????????????.field("title", "new fighting~")
????????????????????.endObject())
????????????.upsert(indexRequest);
????UpdateResponse updateResponse = client.update(updateRequest).get();
????System.out.println("索引名称: " + updateResponse.getIndex());
????System.out.println("文档类型: "+updateResponse.getType());
????System.out.println("ID: "+updateResponse.getId());
????System.out.println("版本: "+updateResponse.getVersion());
????System.out.println("是否创建成功: "+updateResponse.isCreated()); //false
????client.close();
}
----------------------------------------删除文档------------------------------------
prepareDelete
@Test
public void deleteData(){
????DeleteResponse deleteResponse = client.prepareDelete("blog", "article", "3").get();
????System.out.println("索引名称: " + deleteResponse.getIndex());
????System.out.println("文档类型: "+deleteResponse.getType());
????System.out.println("ID: "+deleteResponse.getId());
????System.out.println("版本: "+deleteResponse.getVersion());
????System.out.println("是否删除成功: "+deleteResponse.isFound());
????client.close();
}
----------------------------------------查询文档------------------------------------
安装分词器之前的查询
es提供了queryStringQuery查询
针对多字短的query_string查询
@Test
public void testSearch(){
????SearchResponse searchResponse = client.prepareSearch("blog")
????????????.setTypes("article")
//默认分词器只能查找单个字,并没有把中文进行分词,需要我们安装一个分词器,IK分词器
????????????.setQuery(QueryBuilders.queryStringQuery("更新"))
????????????.get();
????//获取数据的结果对象
????SearchHits hits = searchResponse.getHits();
????//获取命中次数
????System.out.println("查询的结果数据有"+hits.getTotalHits()+"条");
????//遍历所有数据
????Iterator<SearchHit> iterator = hits.iterator();
????while (iterator.hasNext()){
????????SearchHit hit = iterator.next();
????????//获取整条数据
????????System.out.println(hit.getSourceAsString());
????????//获取单个字段
????????System.out.println("id: "+ hit.getSource().get("id"));
????????System.out.println("title: "+ hit.getSource().get("title"));
????????System.out.println("content: "+ hit.getSource().get("content"));
????}
????client.close();
}
原文地址:https://blog.51cto.com/14479068/2428919