Elasticsearch之javaAqi

Stella981
• 阅读 481

一. 创建Maven项目

1.1 导入pom.xml

Elasticsearch之javaAqi

     <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.4.2</version>
        </dependency>

主版本需要与服务器版本一致

1.2 elasticsearch.yml

Elasticsearch之javaAqi

 Elasticsearch之javaAqi

二 . 查询代码实例

2.1 代码
//指定Es集群
          Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
          //创建访问Es服务器的客户端
          TransportClient client = new PreBuiltTransportClient(settings)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300));
  ​
          //数据查询
          GetResponse rs=client.prepareGet("lib","user","AW4ba3-CtOQsl6jnKxI_").get();
          //得到查询出的数据
          System.out.println(rs.getSourceAsString());
          System.out.println("-----------");
          //只取名称
          System.out.println(rs.getSource().get("name"));
          client.close();

三 . 添加文档代码实例

3.1 代码
//指定Es集群
      Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
      //创建访问Es服务器的客户端
      TransportClient client = new PreBuiltTransportClient(settings)
              .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300));
  ​
      //组建文档内容
      XContentBuilder doc=XContentFactory.jsonBuilder()
              .startObject()
              .field("id",1)
              .field("title","java设计模式之装饰模式")
              .field("content","春天,我们去郊游,杏花吹了一头,这是多么惬意和美好,就像美好洒了一头一样。好巧不巧,在这里,"
                      + "碰到一个风流倜傥的男子,我真的好喜欢他。美丽的春日,碰到一见钟情的人,有比这更美好的事吗?")
              .field("postdate","2020-01-09")
              .field("url","http://192.168.95.4:5601/app/kibana#/dev_tools/console?_g=()")
              .endObject();
      //添加文档
      IndexResponse response=client.prepareIndex("lib", "blog","1")
              .setSource(doc).get();
      //返回状态是否添加成功
      System.out.println(response.status());
      //关闭来连接
      client.close();

四. 删除文档代码实例

4.1 .1代码部分
//指定Es集群
          Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
          //创建访问Es服务器的客户端
          TransportClient client = new PreBuiltTransportClient(settings)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300));
          //删除文档
          DeleteResponse rs=client.prepareDelete("lib", "blog","1").get();
  ​
          //返回状态是否删除成功
          System.out.println(rs.status());
          //关闭来连接
          client.close();
4.2.1 存在即修改,不存就报错
//指定Es集群
          Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
          //创建访问Es服务器的客户端
          TransportClient client = new PreBuiltTransportClient(settings)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300));
          //修改文档
          UpdateRequest rqs=new UpdateRequest();
          rqs.index("lib")
          .type("blog")
          .id("1")
          .doc(
                  XContentFactory.jsonBuilder().startObject()
                  .field("title","java设计模式之单列设计模式").endObject()
                  );
  ​
          UpdateResponse rps=client.update(rqs).get();
          //返回状态是否删除成功
          System.out.println(rps.status());
          //关闭来连接
          client.close();
4.2.2 文档不存在就添加,存在就修改
//指定Es集群
        Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
        //创建访问Es服务器的客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"), 9300));
        //修改文档,不存在就添加
        IndexRequest inq=new IndexRequest("lib", "blog", "2")
                .source(
                        XContentFactory.jsonBuilder()
                        .startObject()
                        .field("id",2)
                        .field("title","工厂模式")
                        .field("content","静态工厂,实例工")
                        .field("postdate","2020-02-10")
                        .field("url","http://192.168.95.4:5601/app/kibana#/dev_tools/console?_g=()")
                        .endObject()
                        );
        //先修改,文档不存在执行后面的添加
        UpdateRequest uq=new UpdateRequest("lib", "blog", "3")
                .doc(
                        XContentFactory.jsonBuilder()
                        .startObject()
                        .field("title","设计模式")
                        .endObject()
                        ).upsert(inq);
        //执行操作
        UpdateResponse rps=client.update(uq).get();
        //返回状态是否删除成功
        System.out.println(rps.status());
        //关闭来连接
        client.close();

五.java应用中实现批量操作(mget&bulk)

5.1.1 mget批量查询 ,java代码
           //1.指定es集群
            Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
            //2.创建访问es服务器的客服端
            TransportClient client=new PreBuiltTransportClient(setting)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));//配置查询信息
        MultiGetResponse mget=client.prepareMultiGet()
                .add("lib", "blog", "1")
                .add("lib", "blog", "3").get();
        //展示信息

        for(MultiGetItemResponse ms:mget) {
            GetResponse grp=ms.getResponse();
            if(grp.isExists()&&grp!=null) {
                System.out.println(grp.getSourceAsString());
                System.err.println("___");
                //System.out.println(grp.getSource().get("content"));//指定输出属性
            }
}
5.2.1 bulk批量添加,java代码
       //1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          BulkRequestBuilder bulkbuild=client.prepareBulk();
          //批量添加
          bulkbuild.add(client.prepareIndex("lib1","books","1")
                  .setSource(
                          XContentFactory.jsonBuilder()
                          .startObject()
                          .field("title","python")
                          .field("price", 99)
                          .endObject()
                          )
                  );
          bulkbuild.add(client.prepareIndex("lib1","books","2")
                  .setSource(
                          XContentFactory.jsonBuilder()
                          .startObject()
                          .field("title","vr")
                          .field("price", 39)
                          .endObject()
                          )
                  );
          //执行操作
          BulkResponse rps=bulkbuild.get();
          //执行结果
          System.out.println(rps.status());
          if(rps.hasFailures()) {
              System.out.println("失败了!");
          }
5.3.1 bulk查询符合条件的属性,删除文档,java代码
      //1.指定es集群
              Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
              //2.创建访问es服务器的客服端
              TransportClient client=new PreBuiltTransportClient(setting)
                      .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
              BulkRequestBuilder bulkbuild=client.prepareBulk();
      BulkByScrollResponse rsp=DeleteByQueryAction.INSTANCE
                  .newRequestBuilder(client)
                  .filter(QueryBuilders.matchQuery("title", "设计"))
                  //指定索引
                  .source("lib").get();
          //返回结果,返回影响行数
          long result=rsp.getDeleted();
          System.out.println(result);
5.4.1 全部查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //查询所有
          MatchAllQueryBuilder qd=QueryBuilders.matchAllQuery();
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(qd)
                  .setSize(5).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();

六. java中实现match与multimatch查询

6.1 .1 matc指定条件查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //查询content属性中带有"工厂"的文档,模糊查询,用的ik分词器
          MatchQueryBuilder builder=QueryBuilders.matchQuery("content", "工厂");
          
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(builder)
                  .setSize(5).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
6.2.1 multiMatch多条件查询,java代码
  @Test
      public void multiMatchByElasticsearch() throws IOException {
          //1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //查询content属性title中带有"一见钟情"的文档,模糊查询,用的ik分词器
          MultiMatchQueryBuilder builder=QueryBuilders.multiMatchQuery("一见钟情", "content","title");
          //从全部以lib开始的索引下找,显示5条
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(builder)
                  .setSize(5).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
      }

七.term和terms查询

7.1.1 term条件查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //查询content属性title中带有"静态"的文档,模糊查询,用的ik分词器
          TermQueryBuilder builder=QueryBuilders.termQuery("content","静态");
          //从全部以lib开始的索引下找,显示5条
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(builder)
                  .setSize(5).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
7.2.1 terms多条件查询(指定一个属性配配多个值)
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
      //查询content属性中带有"工厂"或者"春天"的所有文档,一个属性匹配多个值,模糊查询,用的ik分词器
          TermsQueryBuilder builder=QueryBuilders.termsQuery("content","工厂","春天");
          //从全部以lib开始的索引下找,显示5条
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(builder)
                  .setSize(5).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();

八 . java中实现range,prefix,wildcard,fuzzy,type,ids查询

8.1.1 range时间范围查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //range查询,查询postdate时间范围在"2018-01-01~2030-01-01"之间的文档记录
          RangeQueryBuilder builder=QueryBuilders.rangeQuery("postdate").from("2018-01-01").to("2030-01-01").format("yyyy-MM-dd");
          //从全部以lib开始的索引下找,查询所有
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(builder).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
8.2.1 prefix(前缀)查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //prefix查询,查询url内容以http开头的
          PrefixQueryBuilder builder=QueryBuilders.prefixQuery("url","http");
          //从全部以lib开始的索引下找,查询所有
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(builder).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
8.3.1 wildcard(通配符)查询
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //wildcard(通配符)查询,查询content内容有“春日”的文档
          WildcardQueryBuilder builder=QueryBuilders.wildcardQuery("content","*春日*");
          //从全部以lib开始的索引下找,查询所有
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(builder).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
8.4.1 Fuzzy(模糊)查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //fuzzy(模糊)查询,查询content内容有“好巧”的文档
          FuzzyQueryBuilder builder=QueryBuilders.fuzzyQuery("content","更美好");
          //从全部以lib开始的索引下找
          SearchResponse sr=client.prepareSearch("lib*")
                  .setQuery(builder).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
8.5.1 Type(类型)查询,java代码
  //1.指定es集群
        Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
        //2.创建访问es服务器的客服端
        TransportClient client=new PreBuiltTransportClient(setting)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
        //type(类型)查询,查询类型为“blog”的文档
        TypeQueryBuilder builder=QueryBuilders.typeQuery("books");
        //从全部以lib开始的索引下找
        SearchResponse sr=client.prepareSearch("lib*")
                .setQuery(builder).get();
        //查出所有文档
        SearchHits hits=sr.getHits();
        //迭代器打印结果
        Iterator<SearchHit> it=hits.iterator();
        while(it.hasNext()) {
            Map<String,Object> map=it.next().getSourceAsMap();
            for(String key:map.keySet()) {
                System.out.println(key+":"+map.get(key));
            }
            System.out.println("--------------");
        }
        client.close();
8.6.1 Ids查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //ids查询,根据指定的id查询
          IdsQueryBuilder builder=QueryBuilders.idsQuery().addIds("1","2");
          //从全部以lib开始的索引下找
          SearchResponse sr=client.prepareSearch("lib")
                  .setQuery(builder).get();
          //查出所有文档
          SearchHits hits=sr.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();

九 .聚合查询

9.1.1 max最大值查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //Max查询,price(价格)最大值查询
          AggregationBuilder agg=AggregationBuilders.max("aggMax").field("price");
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get();
          //取到最大值
          Max max=rsp.getAggregations().get("aggMax");
          //输出最大值
          System.out.println(max.getName()+":"+max.getValue());
  ​
          client.close();
9.2.1 min最小值查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //min查询,price(价格)最小值查询
          AggregationBuilder agg=AggregationBuilders.min("aggMin").field("price");
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get();
          //取到最小值
          Min min=rsp.getAggregations().get("aggMin");
          //输出最小值
          System.out.println(min.getName()+":"+min.getValue());
  ​
          client.close();
 
9.3.1 avg平均值查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //平均值查询,price(价格)平均值查询
          AggregationBuilder agg=AggregationBuilders.avg("aggAvg").field("price");
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get();
          //取到平均值
          Avg avg=rsp.getAggregations().get("aggAvg");
          //输出平均值
          System.out.println(avg.getName()+":"+avg.getValue());
          client.close();
9.4.1 Sum总和值查询,java代码
//1.指定es集群
      Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
      //2.创建访问es服务器的客服端
      TransportClient client=new PreBuiltTransportClient(setting)
              .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
      //求总和值,price(价格)求总和值查询
      AggregationBuilder agg=AggregationBuilders.sum("aggSum").field("price");
      //从全部以lib开始的索引下找
      SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get();
      //取到总的价格
      Sum sum=rsp.getAggregations().get("aggSum");
      //输出求总和值
      System.out.println(sum.getName()+":"+sum.getValue());
      client.close();
9.5.1 cardinality查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //求基数值
          AggregationBuilder agg=AggregationBuilders.cardinality("aggcardinality").field("price");
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib*").addAggregation(agg).get();
          //取到有多少个基数值
          Cardinality aggcardinality=rsp.getAggregations().get("aggcardinality");
          //输出基数值
          System.out.println(aggcardinality.getName()+":"+aggcardinality.getValue());
          client.close();

十.其他查询

10.1.1 query String 条件查询,指定字段,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //全文查询,查询"python"这本书
          CommonTermsQueryBuilder builder=QueryBuilders.commonTermsQuery("title", "python");
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib*").setQuery(builder).get();
          //取到SearchHits对象
          SearchHits hits=rsp.getHits();
          for(SearchHit hit:hits) {
              System.out.println(hit.getSourceAsString());
          }
          client.close();
10.2.1 query String 全文查询,不指定字段,两边都需要满足,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //全文查询,查询有"工厂"但不包含有"更美好"字段的这个文档
          QueryStringQueryBuilder builder=QueryBuilders.queryStringQuery("+工厂 -更美好");
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib").setQuery(builder).get();
          //取到SearchHits对象
          SearchHits hits=rsp.getHits();
          for(SearchHit hit:hits) {
              System.out.println(hit.getSourceAsString());
          }
          client.close();
 

 
10.3.1 query String 全文查询,满足其中一个,不指定字段,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //全文查询,查询有"工厂"或者不包含有"更美好"字段的这个文档
          SimpleQueryStringBuilder builder=QueryBuilders.simpleQueryStringQuery("+工厂  -更美好");
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib").setQuery(builder).get();
          //取到SearchHits对象
          SearchHits hits=rsp.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
10.4.1 组合查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //组合查询
           BoolQueryBuilder builder=QueryBuilders.boolQuery()
                             .must(QueryBuilders.matchQuery("content","工厂"))//必须包含
                             .mustNot(QueryBuilders.matchQuery("content", "全部"))//不包含
                             .should(QueryBuilders.matchQuery("title", "语法"))//或者包含
                              //时间过滤(大于2020-03-01)
                             .filter(QueryBuilders.rangeQuery("postdate").gte("2020-03-01").format("yyyy-MM-dd"));
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib").setQuery(builder).get();
          //取到SearchHits对象
          SearchHits hits=rsp.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
 
10.5.1 constantScoreQuery查询,java代码
//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //组合查询,查title中包含有“正则”的文档,与termQuery()的作用类似
          ConstantScoreQueryBuilder builder=QueryBuilders.constantScoreQuery(QueryBuilders.termQuery("title","正则"));
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib").setQuery(builder).get();
          //取到SearchHits对象
          SearchHits hits=rsp.getHits();
          //迭代器打印结果
          Iterator<SearchHit> it=hits.iterator();
          while(it.hasNext()) {
              Map<String,Object> map=it.next().getSourceAsMap();
              for(String key:map.keySet()) {
                  System.out.println(key+":"+map.get(key));
              }
              System.out.println("--------------");
          }
          client.close();
 

十一.java应用中实现桶聚合

11.1 分组聚合java代码

/**
       *   桶聚合
       * @throws IOException 
       */
      @Test
      public void Query2Elasticsearch() throws IOException {
          //1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          //按标题分组显示
          AggregationBuilder agg=AggregationBuilders.terms("terms").field("price");
          //从全部以lib开始的索引下找
          SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet();
          //取到分组数据
          Terms  terms=rsp.getAggregations().get("terms");
          for(Terms.Bucket te:terms.getBuckets()) {
              System.out.println(te.getKey()+":"+te.getDocCount());
          }
      }
  }
 

Elasticsearch之javaAqi

11.2 filter聚合(分组过滤)

//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
          ///需要查找price为6666的分组
          TermQueryBuilder query=QueryBuilders.termQuery("price","6666");
          //按标题分组显示
          AggregationBuilder agg=AggregationBuilders.filter("filter",query);
          //从索引lib1下找
          SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet();
          //取到过滤后数据条数
          Filter  filter=rsp.getAggregations().get("filter");
          System.out.println(filter.getDocCount());
  

Elasticsearch之javaAqi

11.3 filters聚合(多个过滤条件)

//1.指定es集群
      Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
      //2.创建访问es服务器的客服端
      TransportClient client=new PreBuiltTransportClient(setting)
              .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
  ​
      //按标题分组显示
      AggregationBuilder agg=AggregationBuilders.filters("filters",
              new FiltersAggregator.KeyedFilter("py", QueryBuilders.termsQuery("title","python")),
              new FiltersAggregator.KeyedFilter("vr", QueryBuilders.termsQuery("title","vr")));
      //从索引lib1下找
      SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet();
      //取到过滤后数据条数
      Filters  filters=rsp.getAggregations().get("filters");
      for(Filters.Bucket filter:filters.getBuckets()) {
          System.out.println(filter.getKey()+":"+filter.getDocCount());
      }

Elasticsearch之javaAqi

11.4 range聚合

//1.指定es集群
      Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
      //2.创建访问es服务器的客服端
      TransportClient client=new PreBuiltTransportClient(setting)
              .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
  ​
      //按标题分组显示
      AggregationBuilder agg=AggregationBuilders.range("range")
              .field("price")
              .addUnboundedTo(60) //小于60以下
              .addRange(1,7000)   //1-7000之间的
              .addUnboundedFrom(50);//大于50以上的
      
      //从索引lib1下找
      SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet();
      //取到过滤后数据条数
      Range  rang=rsp.getAggregations().get("range");
      for(Range.Bucket r:rang.getBuckets()) {
          System.out.println(r.getKey()+":"+r.getDocCount());
      }

Elasticsearch之javaAqi

11.5 missing(统计属性为null的条数,如下其实“prices”这个属性是不存在的)

//1.指定es集群
          Settings setting=Settings.builder().put("cluster.name","my-elasticsearch").build();
          //2.创建访问es服务器的客服端
          TransportClient client=new PreBuiltTransportClient(setting)
                  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.95.4"),9300));
      
          //按标题分组显示
          AggregationBuilder agg=AggregationBuilders.missing("missing").field("prices");
          
          //从索引lib1下找
          SearchResponse rsp=client.prepareSearch("lib1").addAggregation(agg).execute().actionGet();
          //取到过滤后数据条数
          Missing  miss=rsp.getAggregations().get("missing");
          System.out.println(miss.getDocCount());

Elasticsearch之javaAqi

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这