Class ES : 根据 Elasticsearch API 编写的搜索工具类,以下为PHP代码:
ES::$INDEX = 'geo_index';
// 创建包含geo_point类型字段的索引类型
$data = json_encode([
'mappings' => [
'geo_type' => [
'properties' => [
'username' => ['type'=>'text'],
'location' => ['type'=>'geo_point']
]
]
]
]);
$cmd = "curl -XPUT http://192.168.56.101:9200/geo_index -d '{$data}'";
echo shell_exec($cmd);
// 插入数据
$data = json_encode([
'username' => 'xd'.time(),
'location' => [
'lat' => 40.12,
'lon' => -71.34
]
]);
$cmd = "curl -XPOST http://192.168.56.101:9200/geo_index/geo_type -d '{$data}'";
echo shell_exec($cmd);
// 矩形区域搜索
$data = < <<JSON
{
"query": {
"bool": {
"filter": {
"geo_bounding_box": {
"location": {
"top_left": {
"lat": 40.73,
"lon": -74.1
},
"bottom_right": {
"lat": 40.01,
"lon": -71.12
}
}
}
}
}
}
}
JSON;
$response = ES::bodySearch('geo_type', json_decode($data, true));
// 距离搜索
$data = <<<JSON
{
"query": {
"bool": {
"filter": {
"geo_distance": {
"distance": "1000km",
"location": {
"lat": 40.73,
"lon": -74.1
}
}
}
}
},
"sort": [
{
"_geo_distance": {
"location": {
"lat": 40.73,
"lon": -74.1
},
"order": "asc"
}
}
]
}
JSON;
$response = ES::bodySearch('geo_type', json_decode($data, true));
// 多边形区域搜索
$data = <<<JSON
{
"query": {
"bool": {
"filter": {
"geo_polygon": {
"location": {
"points": [
{
"lat": 40,
"lon": -70
},
{
"lat": 30,
"lon": -80
},
{
"lat": 50,
"lon": -90
}
]
}
}
}
}
}
}
JSON;
$response = ES::bodySearch('geo_type', json_decode($data, true));