質問

I am trying to learn ElasticSearch using elastica to connect in and finding information hard to get in order to understand how to query it.

So basically what I am trying to do is, I have inserted data into elastic search, added geo coordinates in and now what i need to do is to be able to run a query that will sort the results i get by closest to farthest.

I wanted to find all the stores in my state, then order them by which one is closest to my current location.

so given a field called "state" and field called "point" which is an array holding long/Lat using elastica what would the query be?

Thanks for any help that you can give me.

役に立ちましたか?

解決

First, you need to map your location field as type geo_point (this needs to be done before inserting any data)

{
    "stores" : {
        "properties" : {
            "point" : {
                "type" : "geo_point"
            }
        }
    }
}

After that, you can simply sort your search by _geo_distance

{
    "sort" : [
        {
            "_geo_distance" : {
                "stores.point" : [-70, 40], // <- reference starting position
                "order" : "asc",
                "unit" : "km"
            }
        }
    ],
    "query" : {
        "match_all" : {}
    }
}

For Elastica, have a look at their docs regarding mapping and query building, and read the unit tests.

他のヒント

For those wanting to sort by distance, this cut down snippet details how to use a custom score:

    $q = new BoolQuery();

    $subQ = new MultiMatchQuery();
    $subQ->setQuery('find me')->setFields(array('foo', 'bar'));
    $q->addShould($subQ);

    $cs = new CustomScore();

    $cs->setScript('-doc["location"].distanceInKm(lat,lon)');
    $cs->addParams(array(
        'lat' => -33.882583,
        'lon' => 151.209737
    ));

    $cs->setQuery($q);

Hope it helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top