ArticleSearchService.php 853 B

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. namespace App\Service;
  3. use Hyperf\Elasticsearch\ClientBuilderFactory;
  4. use Elasticsearch\ClientBuilder;
  5. class ArticleSearchService
  6. {
  7. protected $client;
  8. public function __construct(ClientBuilderFactory $clientBuilderFactory)
  9. {
  10. $this->client = $clientBuilderFactory->create();
  11. }
  12. public function searchArticles($query, $page = 1, $pageSize = 10)
  13. {
  14. $from = ($page - 1) * $pageSize;
  15. $params = [
  16. 'index' => 'articles',
  17. 'body' => [
  18. 'from' => $from,
  19. 'size' => $pageSize,
  20. 'query' => [
  21. 'match' => [
  22. 'title' => $query,
  23. ],
  24. ],
  25. ],
  26. ];
  27. $response = $this->client->search($params);
  28. return $response['hits']['hits'];
  29. }
  30. }