1 | <?php |
||
26 | class SearchCommand extends Command |
||
27 | { |
||
28 | protected static $defaultName = 'fos:elastica:search'; |
||
29 | |||
30 | private $indexManager; |
||
31 | |||
32 | 4 | public function __construct(IndexManager $indexManager) |
|
33 | { |
||
34 | 4 | parent::__construct(); |
|
35 | |||
36 | 4 | $this->indexManager = $indexManager; |
|
37 | 4 | } |
|
38 | |||
39 | 4 | protected function configure() |
|
40 | { |
||
41 | $this |
||
42 | 4 | ->setName('fos:elastica:search') |
|
43 | 4 | ->addArgument('query', InputArgument::REQUIRED, 'The text to search') |
|
44 | 4 | ->addOption('index', null, InputOption::VALUE_REQUIRED, 'The index to search in') |
|
45 | 4 | ->addOption('limit', null, InputOption::VALUE_REQUIRED, 'The maximum number of documents to return', 20) |
|
46 | 4 | ->addOption('show-field', null, InputOption::VALUE_REQUIRED, 'Field to show, null uses the first field') |
|
47 | 4 | ->addOption('show-source', null, InputOption::VALUE_NONE, 'Show the documents sources') |
|
48 | 4 | ->addOption('show-id', null, InputOption::VALUE_NONE, 'Show the documents ids') |
|
49 | 4 | ->addOption('explain', null, InputOption::VALUE_NONE, 'Enables explanation for each hit on how its score was computed.') |
|
50 | 4 | ->setDescription('Searches documents in a given type and index') |
|
51 | ; |
||
52 | 4 | } |
|
53 | |||
54 | protected function execute(InputInterface $input, OutputInterface $output) |
||
55 | { |
||
56 | $indexName = $input->getOption('index'); |
||
57 | $index = $this->indexManager->getIndex($indexName ? $indexName : null); |
||
58 | $query = Query::create($input->getArgument('query')); |
||
59 | $query->setSize($input->getOption('limit')); |
||
60 | if ($input->getOption('explain')) { |
||
61 | $query->setExplain(true); |
||
62 | } |
||
63 | |||
64 | $resultSet = $index->search($query); |
||
65 | |||
66 | $output->writeLn(sprintf('Found %d results', $index->count($query))); |
||
67 | foreach ($resultSet->getResults() as $result) { |
||
68 | $output->writeLn($this->formatResult($result, $input->getOption('show-field'), $input->getOption('show-source'), $input->getOption('show-id'), $input->getOption('explain'))); |
||
69 | } |
||
70 | |||
71 | return 0; |
||
72 | } |
||
73 | |||
74 | /** |
||
75 | * @param Result $result |
||
76 | * @param string $showField |
||
77 | * @param string $showSource |
||
78 | * @param string $showId |
||
79 | * @param string $explain |
||
80 | * |
||
81 | * @return string |
||
82 | */ |
||
83 | protected function formatResult(Result $result, $showField, $showSource, $showId, $explain) |
||
104 | } |
||
105 |