Home  >  Article  >  Backend Development  >  How to use php Elasticsearch to implement location-based search function?

How to use php Elasticsearch to implement location-based search function?

WBOY
WBOYOriginal
2023-09-13 08:29:001332browse

如何利用php Elasticsearch实现基于地理位置的搜索功能?

How to use PHP Elasticsearch to implement location-based search function?

1. Introduction
With the development of the Internet, more and more websites and applications need to implement search functions based on geographical location. For example, a restaurant ordering platform needs to display nearby restaurants based on the user's current location; a travel website needs to display nearby attractions based on the user's departure location; a map navigation application needs to display surrounding parking lots based on the user's destination, etc. wait. The key to achieving this functionality is the ability to efficiently search and sort based on geographic location information.

Elasticsearch is an open source search engine that provides powerful full-text search and analysis capabilities through inverted index and distributed search technology. It has a built-in geographical location search function that can search for nearby points based on latitude and longitude coordinates.

2. Preparation

  1. Installing Elasticsearch
    First, you need to install Elasticsearch on the server. You can visit the official website to download and install the latest version of Elasticsearch.
  2. Install PHP Elasticsearch client library
    PHP Elasticsearch client library is a tool used to interact with Elasticsearch. You can use Composer to install, execute the following command:

    composer require elasticsearch/elasticsearch

3. Create index and mapping
Before starting the search, you need to first create the index and set the mapping.

  1. Create index
    Use the PHP client library provided by Elasticsearch to create an index. The sample code is as follows:

    require 'vendor/autoload.php';
    
    $client = ElasticsearchClientBuilder::create()->build();
    $params = [
        'index' => 'geolocation',
        'body'  => [
            'settings' => [
                'index' => [
                    'number_of_shards'   => 1,
                    'number_of_replicas' => 0,
                ],
            ],
        ],
    ];
    
    $response = $client->indices()->create($params);
  2. Set up mapping
    Before adding documents to the index, you need to define the mapping of field types and attributes. Here we need to add a geolocation mapping for the geolocation field. The sample code is as follows:

    $params = [
        'index' => 'geolocation',
        'body'  => [
            'mappings' => [
                'properties' => [
                    'location' => [
                        'type'       => 'geo_point',
                        'lat_lon'    => true,
                        'geohash'    => true,
                        'geohash_precision' => 5
                    ],
                ],
            ],
        ],
    ];
    
    $response = $client->indices()->putMapping($params);

4. Add documents
Using Elasticsearch's PHP client library, you can follow the steps below to add documents to the index.

  1. Get the latitude and longitude coordinates
    Before adding a document, you need to get the latitude and longitude coordinates of the location. You can use third-party geocoding libraries such as Geocode.xyz or MapQuest.
  2. Add Documents
    Use Elasticsearch’s PHP client library to add the location’s name and latitude and longitude coordinates to the index. The sample code is as follows:

    $params = [
        'index' => 'geolocation',
        'id'    => 1,
        'body'  => [
            'location' => [
                'lat' => 40.7128,
                'lon' => -74.0060,
            ],
            'name' => 'New York City',
        ],
    ];
    
    $response = $client->index($params);

5. Search based on geographical location
By setting search query parameters, you can search based on geographical location.

  1. Set search parameters

    $params = [
        'index' => 'geolocation',
        'body'  => [
            'query' => [
                'bool' => [
                    'must'   => [
                        'match_all' => new stdClass(),
                    ],
                    'filter' => [
                        'geo_distance' => [
                            'distance' => '30km',
                            'location' => [
                                'lat' => 40.7143,
                                'lon' => -74.0060,
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ];
  2. Perform search

    $response = $client->search($params);
    
    foreach ($response['hits']['hits'] as $hit) {
        echo $hit['_id']. ': '. $hit['_source']['name']. PHP_EOL;
    }

This code will return the distance to Documents within 30 kilometers of fixed latitude and longitude coordinates (New York City). Traverse the search results to get the names of places that meet the criteria.

6. Summary
Using PHP Elasticsearch to implement a search function based on geographical location can provide more accurate and convenient geographical location-related information for websites and applications. This functionality is easily accomplished by setting up indexes and mappings, adding documents, and performing geolocation-based searches. In practical applications, the sorting and filtering of search results can be further optimized to improve user experience.

The above is the detailed content of How to use php Elasticsearch to implement location-based search function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn