java操作es进⾏简单的数据增删改
最近研究elasticsearch,因为跟⼩伙伴合作,他搭建服务,我负责写业务,开始对elasticsearch⼀⽆所知,不得不好好研究⼀番。由于我⾃⼰没有进⾏安装,所以安装的博客等亲⾃动⼿以后再写吧,以下是对Elasticsearch的介绍和⼀些在java中的简单使⽤。
⼀、什么是Elasticsearch?
ElasticSearch是⼀个基于Lucene的搜索服务器。它提供了⼀个分布式多⽤户能⼒的全⽂搜索引擎,基于RESTful web接⼝。Elasticsearch是⽤Java开发的,并作为Apache许可条款下的开放源码发布,是当前流⾏的企业级搜索引擎。设计⽤于中,能够达到实时搜索,稳定,可靠,快速,安装使⽤⽅便。(来⾃百度百科)
⼆、如何连接使⽤java进⾏连接和进⾏简单的操作?
直接上代码吧,以下代码都是本⼈写的单元测试,直接拷贝到本地可以查看运⾏的结果。
import java.InetAddress;
import java.UnknownHostException;
import java.util.List;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;java技术介绍百度百科
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.ExistsQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.s.Terms;
import org.elasticsearch.search.s.Terms.Bucket;
import org.elasticsearch.ics.sum.Sum;
import org.elasticsearch.search.sort.SortOrder;
import ansport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.dongao.phoenix.framework.util.JsonUtil;
public class myesTest2 {
public final static String HOST = "127.0.0.1";
// http请求的端⼝是9200,客户端是9300
public final static int PORT = 9300;
static TransportClient client=null;
@Before
public void beforeMethod(){
try {
//获取es连接
Settings setting = Settings.builder()
.put("cluster.name", "ec-elasticsearch")
.put("ansport.sniff", true)//启动嗅探功能
.build();
// 创建client
client = new PreBuiltTransportClient(setting)
client = new PreBuiltTransportClient(setting)
.
addTransportAddresses(new ByName(HOST), PORT));
System.out.println("连接成功!");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
//向es中插⼊⼀条数据
@Test
public  void insert() throws Exception {
//获取es连接
EsTestVo esTestVo = new EsTestVo(2l, "创建客户端1测试数据", "这是⼀条测试数据,可以⽤来进⾏测试");
EsTestVo esvo=new EsTestVo(3l, "张⼀", 5, "张⼀是个好⼈");
EsTestVo esvo1=new EsTestVo(4l, "张⼆", 5, "张⼆是个坏⼈");
EsTestVo esvo2=new EsTestVo(5l, "张三", 20, "张三是个好⼈");
EsTestVo esvo3=new EsTestVo(6l, "张四", 30, "张四是个坏⼈");
EsTestVo esvo5=new EsTestVo(6l, "张五", 30, "张五有点傻");
String json = Json(esvo);
//插⼊数据时不给id赋值,⾃动⽣成id。
IndexResponse response =client.prepareIndex("accesstest", "test01").setSource(json).execute().actionGet();
//多次index这个版本号会变
System.out.println("response.version():"+Version());
}
//根据id查询⽅法测试
@Test
public void getTest() throws Exception{
GetResponse response = client.prepareGet("accesstest", "test01", "1").execute().actionGet();
System.out.Id());
System.out.SourceAsString());
}
//根据条件进⾏查询
@Test
public void searchByQuery(){
//设置搜索的范围(index和type)
SearchRequestBuilder searchBuilder = client.prepareSearch("accesstest").setTypes("test01");
//单词匹配
//  MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", "创建");
TermQueryBuilder matchQuery = Query("name", "张⼀");
//SearchResponse myresponse=responsebuilder.setQuery(QueryBuilders.matchPhraseQuery("title", "molong1208 blog"))
//.setFrom(0).setSize(10).setExplain(true).execute().actionGet();  分页不包头,包尾
SearchResponse reponse = searchBuilder.setQuery(matchQuery).setFrom(0).setSize(6).setExplain(true).execute().actionGet();  //结果展⽰
SearchHits hits = Hits();
for (SearchHit searchHit : hits) {
System.out.SourceAsString());
}
System.out.println("根据条件查询测试");
}
//根据条件进⾏查询--多词条查询
@Test
public void searchByQuery1(){
//设置搜索的范围(index和type)
SearchRequestBuilder searchBuilder = client.prepareSearch("accesstest").setTypes("test01");
//单词匹配
//SearchResponse myresponse=responsebuilder.setQuery(QueryBuilders.matchPhraseQuery("title", "molong1208 blog"))
//.setFrom(0).setSize(10).setExplain(true).execute().actionGet();  分页不包头,包尾
SearchResponse reponse = searchBuilder.setQuery(QueryBuilders.multiMatchQuery("测试","name","des")).execute().actionGet(); //  SearchResponse reponse = searchBuilder.setQuery(QueryBuilders.matchAllQuery()).execute().actionGet();
//结果展⽰
SearchHits hits = Hits();
for (SearchHit searchHit : hits) {
System.out.SourceAsString());
}
System.out.println("根据条件查询测试");
System.out.println("根据条件查询测试");
}
@Test  //多索引多类型查询,可以同时查询两个索引中的两个type中的数据
public void searchByQuery2(){
SearchRequestBuilder searchBulders = client.prepareSearch("accesstest","accesstest_01").setTypes("test01","test01");
SearchResponse searchResponse =
searchBulders.setQuery(QueryBuilders.matchAllQuery())
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setFrom(0).setSize(20)
.execute().actionGet();
SearchHits hits = Hits();
for (SearchHit searchHit : hits) {
System.out.SourceAsString());
}
}
//范围查询  +排序
/*
* 经查询发现范围查询有两种⽅法。⼀个是使⽤QueryBuilders直接调⽤使⽤,还有⼀个是使⽤ .setPostFilter(FilterBuilders.rangeFilter("age").gte(18).lte(22))  * 第⼆种⽅法没有试验
*/
@Test
public void searchByquery3(){
SearchRequestBuilder builder = client.prepareSearch("accesstest").setTypes("test01");
//第⼀种直接调⽤
SearchResponse searchResponse =
builder.setQuery(QueryBuilders.rangeQuery("age").gt(10))
.addSort("id",SortOrder.DESC)
.get();
SearchHits hits = Hits();
for (SearchHit searchHit : hits) {
System.out.SourceAsString());
}
}
@After
public void close(){
client.close();
System.out.println("关闭成功");
}
//根据id删除数据测试
@Test
public void deleteTest() throws Exception{
//获取es连接
Settings setting = Settings.builder().put("cluster.name", "ec-elasticsearch").build();
// 创建client
TransportClient client = new PreBuiltTransportClient(setting)
.addTransportAddresses(new ByName(HOST), PORT));
DeleteResponse response = client.prepareDelete("accesstest", "test01", "2").execute().actionGet();
System.out.Id());
System.out.Result());
client.close();
}
//删除索引
@SuppressWarnings("unchecked")
@Test
public void deleteIndex() throws Exception{
//删除的⽅法
DeleteIndexResponse response = client.admin().indices().prepareDelete("accesslog").execute().actionGet();
//判断是否删除成功,成功为true,失败是false
System.out.println( response.isAcknowledged());;
client.close();
}
}
代码格式有点乱,还望⼤家见谅。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。