Vapor 的 Elasticsearch 服务

Swift Vapor

这个库允许你从你的 Vapor 应用程序连接到 Elasticsearch 服务器,执行搜索并获取 Codable/Content 结果。目前只支持搜索,不支持索引和数据操作。

设置

将 Elasticsearch 服务添加到你的 Package.swift 文件中

.package(url: "https://github.com/monstar-lab/elasticsearch-service.git", from: "0.9.0")

在你的 configure.swift 文件中注册配置对象和 provider

let elasticURL = URL(string: "https://:9200")

if let elasticURL = elasticURL {
  let elasticConfig = ElasticsearchConfig(serverURL: elasticURL)
  services.register(elasticConfig)

  try services.register(ElasticsearchProvider())
}

使用服务

导入 ElasticsearchService 并从你的容器中获取 ElasticsearchClient 实例后,你可以发送你的搜索请求(可以包装在 QueryContainer 中,或者对于复杂的查询,可以使用简单的 [AnyHashable: Any]),并接收搜索结果(同样可以作为自定义 Codable 结构,或者作为 [AnyHashable: Any])。

QueryContainer 和符合 Query 协议的 struct 允许你以类型安全、Swift 风格的方式建模你的查询。然而,并非 Elasticsearch 的所有查询语言都被转换了,只有最常用的查询。如果缺少你需要的查询,请随意提交 pull request。

func getSearchHandler(_ req: Request) throws -> Future<[Product]> {
  let elasticClient = try req.make(ElasticsearchClient.self)
  let query = QueryContainer(
    Query(
      Fuzzy(key: "name", value: "bolster", transpositions: true)
    )
  )

  return try elasticClient
    .search(index: "product", query, decodeTo: Product.self)
    .map(to: [Product].self) { result in
      return result.hits.hits.map { $0.source }
    }
}

更多示例,请随时查看测试套件或注释。

已知问题