public int getNbrInstance() {
   String query =
       "{\n"
           + "   \"query\": {\n"
           + "       \"match_all\": {}\n"
           + "   },\n"
           + "   \"size\": "
           + Integer.MAX_VALUE
           + "\n"
           + "}";
   String elasticType = "test-ES";
   SearchResult searchResult = performSearchOnType(query, elasticType);
   System.out.println(elasticType);
   JsonObject jsonObject = searchResult.getJsonObject();
   JsonArray jsonHits = jsonObject.get("hits").getAsJsonObject().get("hits").getAsJsonArray();
   System.out.println();
   return jsonHits.size();
 }
コード例 #2
0
  private <T> List<GeolocResult<T>> find(
      double lat, double lon, int size, Class<T> clazz, String elasticType) {
    if (size == 0) {
      size = 10;
    }

    String query =
        "{\n"
            + "  \"query\": {\n"
            + "    \"filtered\" : {\n"
            + "        \"filter\" : {\n"
            + "            \"geo_distance\" : {\n"
            + "                \"distance\" : \"200km\",\n"
            + "                \"location\" : {\n"
            + "                    \"lat\" : "
            + lat
            + ",\n"
            + "                    \"lon\" : "
            + lon
            + "\n"
            + "                }\n"
            + "            }\n"
            + "        }\n"
            + "    }\n"
            + "  },\n"
            + "  \"size\" : "
            + size
            + ",\n"
            + "  \"sort\": [\n"
            + "    {\n"
            + "      \"_geo_distance\": {\n"
            + "        \"location\": { \n"
            + "            \"lat\" : "
            + lat
            + ",\n"
            + "            \"lon\" : "
            + lon
            + "\n"
            + "        },\n"
            + "        \"order\":         \"asc\",\n"
            + "        \"unit\":          \"km\", \n"
            + "        \"distance_type\": \"plane\" \n"
            + "      }\n"
            + "    }\n"
            + "  ]\n"
            + "}";

    SearchResult searchResult = performSearchOnType(query, elasticType);

    JsonObject jsonObject = searchResult.getJsonObject();
    JsonArray jsonHits = jsonObject.get("hits").getAsJsonObject().get("hits").getAsJsonArray();

    Gson gson = new Gson();

    return StreamSupport.stream(jsonHits.spliterator(), false)
        .map(
            jsonElement -> {
              JsonObject hit = jsonElement.getAsJsonObject();
              double distance = hit.get("sort").getAsDouble();
              T result = gson.fromJson(hit.get("_source").getAsJsonObject(), clazz);

              return new GeolocResult<T>(result, (int) (distance * 1000));
            })
        .collect(Collectors.toList());
  }