java操作ElasticSearch简单实用教程

1、简单介绍
ElasticSearch(ES)是为了解决原生lucene实用的不足,相比lucene,其使用更加简单;
其特点有:
分布式的实时文件存储,每个字段都被索引并可被搜索
分布式的实时分析搜索引擎
可以扩展到上百台服务器,处理PB级结构化或非结构化数据
高度集成化的服务,你的应用可以通过简单的 RESTful API、各种语言的客户端甚至命令行与之
交互。
上手Elasticsearch非常容易。它提供了许多合理的缺省值,并对初学者隐藏了复杂的搜索引擎理论。它拥有开瓶即饮的效果(安装即可使用),只需很少的学习既可在生产环境中使用。
2、安装ES
① 下载ES安装包
官方下载地址:https://www.elastic.co/downloads/elasticsearch
绿色版,解压即可使用
② 运行ES
bin/elasticsearch.bat
③ 验证
访问:http://localhost:9200/
出现上述信息则表示安装成功
3、java API操作
①获取client方法

  public static TransportClient getClient() throws Exception {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));        return client;
    }

②创建索引方式

 @Test
    public void testES() throws Exception{
        //获取连接
        TransportClient client = getClient();
        //创建索引库
        IndexRequestBuilder indexRequestBuilder =
                client.prepareIndex("school", "room", "1");
        Map map=new HashMap();
        map.put("id",1 );
        map.put("name","math" );
        map.put("num",50 );
        //写索引
        IndexResponse indexResponse =  indexRequestBuilder.setSource(map).get();
        client.close();
        System.out.println(indexResponse);
    }

③获取索引

@Test
    public void testGET() throws Exception{
        TransportClient client = getClient();
        GetResponse response = client.prepareGet("school", "room", "1").get();
        System.out.println(response.getSource());
    }

④更新索引

@Test
    public void testUpdate() throws Exception{
        TransportClient client = getClient();
        Map map=new HashMap();
        map.put("id",1 );
        map.put("name","chinese" );
        map.put("num",50 );
        UpdateResponse updateResponse = client.prepareUpdate("school", "room", "1").setDoc(map).get();
        System.out.println(updateResponse);
    }

⑤删除索引

@Test
    public void testDelete() throws Exception{
        TransportClient client = getClient();
        DeleteResponse deleteResponse = client.prepareDelete("school", "room", "1").get();
        System.out.println(deleteResponse);
    }

⑥批量操作

@Test
    public void testBatch() throws Exception{
        TransportClient client = getClient();
        //获取批量请求对象
        BulkRequestBuilder bulk = client.prepareBulk();
        for (int i = 0; i <10 ; i++) {
            Map map=new HashMap();
            map.put("name","曦茉乖宝宝"+i );
            map.put("age",1+i );
            bulk.add(client.prepareIndex("user", "people",i+"" ).setSource(map));
        }
        BulkResponse bulkItemResponses = bulk.get();
        if(bulkItemResponses.hasFailures()){
            System.out.println("youcuo");
        }
        client.close();
    }

⑦查询索引

 @Test
    public void testSearch() throws Exception{
        TransportClient client = getClient();
        //获取bool对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//     List<QueryBuilder> must = boolQueryBuilder.must();
//        must.add(QueryBuilders.matchQuery("name","曦茉乖宝宝4" ));
        //获取过滤器
        List<QueryBuilder> filter = boolQueryBuilder.filter();
        //设置过滤条件
        filter.add(QueryBuilders.rangeQuery("age").gte(3).lte(10));
        //设置分页排序
        SearchResponse response = client.prepareSearch("user").setFrom(1).setSize(3).setQuery(boolQueryBuilder)
                .addSort("age", SortOrder.DESC).get();
        System.out.println(response.getHits().getTotalHits());
        SearchHit[] hits = response.getHits().getHits();
        // 循环数据结构
        for (SearchHit hit : hits) {
            System.out.println(hit.getSource());
        }
        // 关闭资源
        client.close();
    }

猜你喜欢

转载自blog.csdn.net/weixin_44832841/article/details/89578081