2

I have read and tried https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

I am using drupal 8 and using the default content index for testing. I am able to run the following code and I get a result count, but not result items.

$index = \Drupal\search_api\Entity\Index::load('default_index');
$query = $index->query();

// Change the parse mode for the search.
$parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
  ->createInstance('direct');
$parse_mode->setConjunction('OR');
$query->setParseMode($parse_mode);

// Set fulltext search keywords and fields.
$query->keys('');
$query->setFulltextFields(['title', 'name', 'body']);

// Do paging.
$query->range(20, 10);

// Set one or more tags for the query.
// @see hook_search_api_query_TAG_alter()
// @see hook_search_api_results_TAG_alter()
$query->addTag('custom_search');

// Execute the search.
$results = $query->execute();

echo "Result count: {$results->getResultCount()}\n";
$ids = implode(', ', array_keys($results->getResultItems()));
echo "Returned IDs: $ids.\n";

Count shows a value but I can't get any result items. I tried with $query->keys(''); $query->keys('*'); and some value $query->keys('some value'); In all cases the count seems to be correct. The search therefore seems to be executed correctly, but how can I retrieve the items?

1

3 Answers 3

1
    //first just run this line
    kint($results);
    //and then you can uncomment the next lines, in my case I needed the response key 'elasticsearch_response'
    $response = $results->getExtraData('elasticsearch_response', []);
    $hits = $response['hits']['hits'];
    foreach($hits as $hit){
      kint($hit);
    }
1

Just found this old post while debugging the same issue. Adding my fix in case other hit it too..

The problem I ran into using the sample code was this line:

// Do paging.
$query->range(20, 10);

I since I only had a few records in my database, there wasn't 20+ records, the total count was correct, but couldn't page that far.

Updating to:

// Do paging.
$query->range(0, 10);

Fixed my issue.

0

You need to iterate and get them. Here is one way I did it:

$results = $query->execute();
$output = '';

foreach ($results as $result) {
  $value = $result->getField('fieldname')->getValues();
  $output .= $value[0];
}
1
  • That's not working for me. The foreach is not processed at all as there are no items in $results. implode(', ', array_keys($results->getResultItems())); should do the same by way. But both do not work. The strange thing is that the result counter is correct. Depending on my search key the number of results is always correct. But I can't access the items.
    – Thomas0878
    Commented Jan 10, 2018 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.