Scala 语言 实战 Play 框架集成 Elasticsearch 商品搜索接口开发

Scala阿木 发布于 2025-06-10 10 次阅读


Scala语言实战:Play框架集成Elasticsearch实现商品搜索接口开发

随着互联网的快速发展,大数据和搜索引擎技术已经成为现代企业提高用户体验、提升业务效率的关键。在Scala语言和Play框架的强大支持下,结合Elasticsearch搜索引擎,我们可以轻松实现高效、可扩展的商品搜索接口。本文将围绕这一主题,详细介绍如何在Play框架中集成Elasticsearch,并实现一个商品搜索接口。

环境准备

在开始之前,我们需要准备以下环境:

1. Scala环境:建议使用Scala 2.12或更高版本。
2. Play框架:建议使用Play 2.6或更高版本。
3. Elasticsearch:建议使用Elasticsearch 7.x版本。
4. Java环境:Elasticsearch需要Java环境,建议使用Java 8或更高版本。

1. 创建Play项目

我们需要创建一个Play项目。可以使用sbt(Scala Build Tool)来创建一个Play项目。

shell
sbt new playframework/play-java-seed.g8

然后,进入项目目录,并启动sbt:

shell
cd my-play-project
sbt

2. 添加Elasticsearch依赖

在`build.sbt`文件中,添加Elasticsearch的依赖项:

scala
libraryDependencies ++= Seq(
"com.typesafe.play" %% "play-json" % "2.9.2",
"org.elasticsearch" % "elasticsearch" % "7.10.1",
"org.elasticsearch.client" % "elasticsearch-rest-high-level-client" % "7.10.1"
)

3. 配置Elasticsearch

在`application.conf`文件中,配置Elasticsearch的连接信息:

conf
elasticsearch.host = localhost
elasticsearch.port = 9200

4. 创建商品实体类

在`models`目录下创建一个商品实体类`Product.scala`:

scala
package models

import play.api.libs.json.Json

case class Product(id: String, name: String, price: Double, description: String)

object Product {
implicit val productFormat = Json.format[Product]
}

5. 创建Elasticsearch客户端

在`controllers`目录下创建一个Elasticsearch客户端类`ElasticsearchClient.scala`:

scala
package controllers

import com.typesafe.play.json.Json
import org.elasticsearch.client.RestHighLevelClient
import org.elasticsearch.client.RequestOptions
import org.elasticsearch.client.core.CountRequest
import org.elasticsearch.client.core.CountResponse
import org.elasticsearch.index.query.QueryBuilders
import org.elasticsearch.search.builder.SearchSourceBuilder

class ElasticsearchClient {
val client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
)

def countProducts(): CountResponse = {
val countRequest = new CountRequest("products")
countRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()))
client.count(countRequest, RequestOptions.DEFAULT)
}

def searchProducts(query: String, size: Int, from: Int): Seq[Product] = {
val searchRequest = new SearchRequest("products")
searchRequest.source(new SearchSourceBuilder()
.query(QueryBuilders.matchQuery("name", query))
.size(size)
.from(from)
)
val searchResponse = client.search(searchRequest, RequestOptions.DEFAULT)
val hits = searchResponse.getHits
val products = hits.getHits.map(hit => Json.parse(hit.getSourceAsString()).as[Product])
products
}

def close(): Unit = {
client.close()
}
}

6. 创建商品搜索接口

在`controllers`目录下创建一个商品搜索控制器`ProductSearchController.scala`:

scala
package controllers

import models.Product
import play.api.mvc._
import scala.concurrent.ExecutionContext.Implicits.global

class ProductSearchController extends Controller {
val esClient = new ElasticsearchClient()

def search(query: String, size: Int, from: Int): Action[Result] = Action.async {
val products = esClient.searchProducts(query, size, from)
Ok(Json.toJson(products))
}

def count(): Action[Result] = Action.async {
val count = esClient.countProducts()
Ok(Json.toJson(count.getCount))
}
}

7. 配置路由

在`conf/routes`文件中,配置商品搜索接口的路由:

scala
GET /search controllers.ProductSearchController.search
GET /count controllers.ProductSearchController.count

8. 运行项目

启动sbt,并运行Play项目:

shell
sbt run

现在,我们可以通过访问`http://localhost:9000/search?query=商品名称&size=10&from=0`来搜索商品,或者访问`http://localhost:9000/count`来获取商品总数。

总结

本文介绍了如何在Play框架中集成Elasticsearch,并实现一个商品搜索接口。通过以上步骤,我们可以快速搭建一个高效、可扩展的商品搜索系统。在实际项目中,可以根据需求调整Elasticsearch的配置、索引和查询策略,以实现更精准、更高效的搜索效果。