From d1407950b599989e1a6838c768d446bd5f17ab95 Mon Sep 17 00:00:00 2001 From: ornicar Date: Mon, 25 Apr 2011 12:31:43 -0700 Subject: [PATCH] Add explain capabilities to the search command --- Command/SearchCommand.php | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Command/SearchCommand.php b/Command/SearchCommand.php index 2da723f..48106f5 100644 --- a/Command/SearchCommand.php +++ b/Command/SearchCommand.php @@ -29,6 +29,7 @@ class SearchCommand extends Command ->addOption('index', null, InputOption::VALUE_NONE, 'The index to search in') ->addOption('limit', null, InputOption::VALUE_REQUIRED, 'The maximum number of documents to return', 20) ->addOption('show-source', null, InputOption::VALUE_NONE, 'Show the documents sources') + ->addOption('explain', null, InputOption::VALUE_NONE, 'Enables explanation for each hit on how its score was computed.') ->setName('foq:elastica:search') ->setDescription('Searches documents in a given type and index'); } @@ -42,22 +43,27 @@ class SearchCommand extends Command $type = $index->getType($input->getArgument('type')); $query = Elastica_Query::create($input->getArgument('query')); $query->setLimit($input->getOption('limit')); + if ($input->getOption('explain')) { + $query->setExplain(true); + } $resultSet = $type->search($query); $output->writeLn(sprintf('Found %d results', $type->count($query))); foreach ($resultSet->getResults() as $result) { - $output->writeLn($this->formatResult($result, $input->getOption('show-source'))); + $output->writeLn($this->formatResult($result, $input->getOption('show-source'), $input->getOption('explain'))); } } - protected function formatResult(Elastica_Result $result, $showSource) + protected function formatResult(Elastica_Result $result, $showSource, $explain) { $source = $result->getSource(); + $string = sprintf('[%0.2f] %s', $result->getScore(), var_export(reset($source), true)); if ($showSource) { - $string = sprintf('[%0.2f] %s %s', $result->getScore(), var_export(reset($source), true), json_encode($source)); - } else { - $string = sprintf('[%0.2f] %s', $result->getScore(), var_export(reset($source), true)); + $string = sprintf('%s %s', $string, json_encode($source)); + } + if ($explain) { + $string = sprintf('%s %s', $string, json_encode($result->getExplanation())); } return $string;