d03ef3ecb317b3f280684b54d939d8b34be95e86
[phorkie.git] / src / phorkie / Search / Elasticsearch.php
1 <?php
2 namespace phorkie;
3
4 class Search_Elasticsearch
5 {
6     public function __construct()
7     {
8         $this->searchInstance = $GLOBALS['phorkie']['cfg']['elasticsearch'];
9     }
10
11     /**
12      * Search for a given term and return repositories that contain it
13      * in their description, file names or file content
14      *
15      * @param string  $term    Search term
16      * @param integer $page    Page of search results, starting with 0
17      * @param integer $perPage Number of results per page
18      *
19      * @return Search_Result Search result object
20      */
21     public function search($term, $page = 0, $perPage = 10)
22     {
23         $r = new \HTTP_Request2(
24             $this->searchInstance . 'repo/_search',
25             \HTTP_Request2::METHOD_GET
26         );
27         $r->setBody(
28             json_encode(
29                 (object)array(
30                     'from' => $page * $perPage,
31                     'size' => $perPage,
32                     'query' => (object)array(
33                         'bool' => (object)array(
34                             'should' => array(
35                                 (object)array(
36                                     'query_string' => (object)array(
37                                         'query' => $term
38                                     ),
39                                 ),
40                                 (object)array(
41                                     'has_child' => (object)array(
42                                         'type'         => 'file',
43                                         'query' => (object)array(
44                                             'query_string' => (object)array(
45                                                 'query' => $term
46                                             )
47                                         )
48                                     )
49                                 )
50                             )
51                         )
52                     )
53                 )
54             )
55         );
56         //FIXME: error handling
57         $httpRes = $r->send();
58         $jRes = json_decode($httpRes->getBody());
59
60         $sres = new Search_Result();
61         $sres->results = $jRes->hits->total;
62         $sres->page    = $page;
63         $sres->perPage = $perPage;
64
65         foreach ($jRes->hits->hits as $hit) {
66             $r = new Repository();
67             //FIXME: error handling. what about deleted repos?
68             $r->loadById($hit->_source->id);
69             $sres->repos[] = $r;
70         }
71
72         return $sres;
73     }
74 }
75
76 ?>