Клиент высокого уровня Elasticsearch не смог отобразить geo_point - PullRequest
0 голосов
/ 03 марта 2020

У меня есть заявка на использование упругого поиска геопространственных. Я использую клиент эластичного поиска для индексации и поиска документов. Когда я индексировал поле geo_point в elasti c, я не мог их искать. Я получаю исключение.

Мой класс объектов;

import lombok.Data;
import org.elasticsearch.common.geo.GeoPoint;
import javax.persistence.Id;

@Data
public class CustomerLocation {
    @Id
    private String id;

    private Integer cifNo;

    private String userId;

    private String status;

    private String sessionId;

    private Integer locationCount;

    private String lastSeenDate;

    private String firstSeenDate;

    private GeoPoint geoPoint;
}

метод создания индекса;

public void save(CustomerLocation customerLocation) throws IOException {
    IndexRequest indexRequest = new IndexRequest("customerlocation").id(customerLocation.getId()).source(objectMapper.writeValueAsString(customerLocation),XContentType.JSON);
    client.index(indexRequest, RequestOptions.DEFAULT);
}

Отображение индекса;

{
    "customerlocation": {
        "mappings": {
            "properties": {
                "cifNo": {
                    "type": "long"
                },
                "firstSeenDate": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "geoPoint": {
                    "properties": {
                        "fragment": {
                            "type": "boolean"
                        },
                        "geohash": {
                            "type": "text",
                            "fields": {
                                "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                }
                            }
                        },
                        "lat": {
                            "type": "float"
                        },
                        "lon": {
                            "type": "float"
                        }
                    }
                },
                "id": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "lastSeenDate": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "locationCount": {
                    "type": "long"
                },
                "status": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                }
            }
        }
    }
}

И поле геопункта не является типом geo_point. Когда я ищу местоположение с радиусом следующих линий:

public List<CustomerLocation> findByCifNoAndUserIdWithinLocation(GenericRequest genericRequest, Integer radius) {

    List<CustomerLocation> customerLocationList = new ArrayList<>();
    try {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        SearchRequest searchRequest = new SearchRequest("customerlocation");

        QueryBuilder query;
        if(genericRequest.getUserId()!=null) {
            query = QueryBuilders.boolQuery().
                    filter(QueryBuilders.termQuery("cifNo",genericRequest.getClientNo())).
                    filter(QueryBuilders.termQuery("userId",genericRequest.getUserId()));
        } else {
            query = QueryBuilders.boolQuery().
                    filter(QueryBuilders.termQuery("cifNo",genericRequest.getClientNo()));
        }
        QueryBuilder geoDistanceQueryBuilder = QueryBuilders
                .geoDistanceQuery("geoPoint")
                .point(genericRequest.getLatitude(), genericRequest.getLongitude())
                .distance(radius, DistanceUnit.KILOMETERS);

        QueryBuilder finalQuery = QueryBuilders.boolQuery().must(query).filter(geoDistanceQueryBuilder);
        sourceBuilder.query(finalQuery);
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit searchHit:hits) {
            CustomerLocation customerLocation = objectMapper.readValue(searchHit.getSourceAsString(),CustomerLocation.class);
            if(customerLocation.getStatus()!=null && !customerLocation.getStatus().equalsIgnoreCase("alert")) {
                customerLocationList.add(customerLocation);
            } else if (customerLocation.getStatus()==null) {
                customerLocationList.add(customerLocation);
            }
        }
    } catch (Exception e) {
        log.error("[{}]Exception occured while getting customer location from elastic",genericRequest.getClientNo(),e);
    }
    return customerLocationList;
}

я получаю ниже исключения при запуске выше кода. В чем моя ошибка?

org.elasticsearch.ElasticsearchStatusException: Elasticsearch exception [type=search_phase_execution_exception, reason=all shards failed]
    at org.elasticsearch.rest.BytesRestResponse.errorFromXContent(BytesRestResponse.java:177) ~[elasticsearch-7.5.2.jar:7.5.2]
    at org.elasticsearch.client.RestHighLevelClient.parseEntity(RestHighLevelClient.java:1793) ~[elasticsearch-rest-high-level-client-7.5.2.jar:7.5.2]
    at org.elasticsearch.client.RestHighLevelClient.parseResponseException(RestHighLevelClient.java:1770) ~[elasticsearch-rest-high-level-client-7.5.2.jar:7.5.2]
    at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1527) ~[elasticsearch-rest-high-level-client-7.5.2.jar:7.5.2]
    at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1484) ~[elasticsearch-rest-high-level-client-7.5.2.jar:7.5.2]
    at org.elasticsearch.client.RestHighLevelClient.performRequestAndParseEntity(RestHighLevelClient.java:1454) ~[elasticsearch-rest-high-level-client-7.5.2.jar:7.5.2]
    at org.elasticsearch.client.RestHighLevelClient.search(RestHighLevelClient.java:970) ~[elasticsearch-rest-high-level-client-7.5.2.jar:7.5.2]
    at com.ykb.frd.fraudlocation.elastic.repository.CustomerLocationRepositoryImpl.findByCifNoAndUserIdWithinLocation(CustomerLocationRepositoryImpl.java:61) ~[classes/:na]
    at com.ykb.frd.fraudlocation.elastic.repository.CustomerLocationRepositoryImpl$$FastClassBySpringCGLIB$$8bf452.invoke(<generated>) [classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) [spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769) [spring-aop-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) [spring-aop-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) [spring-aop-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) [spring-tx-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) [spring-aop-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) [spring-aop-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) [spring-aop-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at com.ykb.frd.fraudlocation.elastic.repository.CustomerLocationRepositoryImpl$$EnhancerBySpringCGLIB$$ad3f68fd.findByCifNoAndUserIdWithinLocation(<generated>) [classes/:na]
    at com.ykb.frd.fraudlocation.elastic.ElasticServiceImpl.getCustomersLocationsIndexWithinLocation(ElasticServiceImpl.java:30) [classes/:na]
    at com.ykb.frd.fraudlocation.ElasticTest.elasticDataLocationFoundTest(ElasticTest.java:44) [test-classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.12.jar:4.12]

1 Ответ

0 голосов
/ 04 марта 2020

В вашем отображении не указано ваше поле GeoPoint с отображением geo_point .

Настройте его следующим образом

...
{
  "geoPoint":{
    "properties":{

      ...

      "lat":{
        "type":"float"
      },
      "lon":{
        "type":"float"
      },

      "as_geopoint": {         <-----
        "type": "geo_point"
      }
    }
  }
}
...

и подготовьте Ваши документы должны выглядеть следующим образом:

{
  ...
  "geoPoint": {
    ...
    "as_geopoint": {
       "lat": 41.12,
       "lon": -71.34
    }
  }
}

, а затем выполнить запрос к полю geoPoint.as_geopoint.

Вам нужно проиндексировать свои геоданные, прежде чем вы сможете выполнить гео-запрос к ним!

...