How to use Elasticsearch and PHP for music search and recommendation
Overview
On music streaming platforms, it is crucial to achieve fast and accurate music search and personalized recommendations. Elasticsearch is a popular open source search and analytics engine that works well for building such a system. This article will introduce how to use Elasticsearch and PHP to implement music search and recommendation functions, and provide relevant code examples.
# 安装Elasticsearch $ wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{version}.tar.gz $ tar -xvf elasticsearch-{version}.tar.gz $ cd elasticsearch-{version}/bin $ ./elasticsearch # 创建索引和映射 $ curl -XPUT 'http://localhost:9200/music' -H 'Content-Type: application/json' -d ' { "mappings": { "properties": { "title": { "type": "text" }, "artist": { "type": "text" }, "genre": { "type": "keyword" } } } } '
require 'vendor/autoload.php'; $hosts = ['localhost:9200']; $client = ElasticsearchClientBuilder::create()->setHosts($hosts)->build(); // 导入音乐数据 $music1 = [ 'title' => 'Song 1', 'artist' => 'Artist 1', 'genre' => 'Pop' ]; $music2 = [ 'title' => 'Song 2', 'artist' => 'Artist 2', 'genre' => 'Rock' ]; $params = [ 'index' => 'music', 'id' => 1, 'body' => $music1 ]; $response = $client->index($params); $params = [ 'index' => 'music', 'id' => 2, 'body' => $music2 ]; $response = $client->index($params);
match
query. The following is a sample code snippet: // 执行搜索 $params = [ 'index' => 'music', 'body' => [ 'query' => [ 'match' => [ 'title' => 'song' ] ] ] ]; $response = $client->search($params); // 处理搜索结果 foreach ($response['hits']['hits'] as $hit) { $music = $hit['_source']; echo 'Title: ' . $music['title'] . ', Artist: ' . $music['artist'] . ', Genre: ' . $music['genre']; echo " "; }
more_like_this
query to find music that is similar to a given music. The following is a sample code snippet: // 执行推荐查询 $params = [ 'index' => 'music', 'body' => [ 'query' => [ 'more_like_this' => [ 'fields' => ['title', 'artist'], 'like' => [ '_index' => 'music', '_id' => 1 ] ] ] ] ]; $response = $client->search($params); // 处理推荐结果 foreach ($response['hits']['hits'] as $hit) { $music = $hit['_source']; echo 'Title: ' . $music['title'] . ', Artist: ' . $music['artist'] . ', Genre: ' . $music['genre']; echo " "; }
Summary
By combining Elasticsearch and PHP, we can easily implement music search and personalized recommendation functions. In this article, we introduce how to set up Elasticsearch, import music data, implement music search functions and music recommendation functions, and provide corresponding code examples. Hope this article helps you build a better music streaming platform.
The above is the detailed content of How to use Elasticsearch and PHP for music search and recommendations. For more information, please follow other related articles on the PHP Chinese website!