(24) ElasticSearch java project portfolio query example

  Query field contains changge interests and does not contain lvyou, or address field contains bei jing documents, and both must meet in front of birthday> = "1980-01-01"

@Test
    public void testBoolQuery() throws IOException, InterruptedException, ExecutionException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress ( new new TransportAddress (InetAddress.getByName ( "192.168.43.151"), 9300 ));
         // create a query object query field contains changge interests and does not contain lvyou, bei jing or address field contains the document, and the first two must satisfy Birthday> = "1980-01-01" 
        QueryBuilder qb = QueryBuilders.boolQuery ()
                          .must(QueryBuilders.matchQuery("interests","changge"))
                          .mustNot(QueryBuilders.matchQuery("interests","lvyou"))
                          .should(QueryBuilders.matchQuery("address", "bei jing"))
                          .filter(QueryBuilders.rangeQuery("birthday").gte("1980-01-01").format("yyyy-MM-dd"));
        //执行查询
        SearchResponse sr = client.prepareSearch("lib3")
                                  .setQuery(qb)
                                  .get();
        // Get a result 
        SearchHits Hits = sr.getHits ();
         for (SearchHit HIT: Hits) {
             // output json 
            System.out.println (hit.getSourceAsString ());
             // output json with the key value 
            the Map <String, Object> Map = hit.getSourceAsMap ();
             for (String Key: map.keySet ()) {
                System.out.println(key+"="+map.get(key));
            }
        }
        client.close();
   }

Guess you like

Origin www.cnblogs.com/javasl/p/12081814.html