TransWikia.com

How do I get only node IDs from the search results?

Drupal Answers Asked on October 26, 2021

I’m using Search API Solr with custom searches in code, but I want to find a way to limit the return results to only the nid to save on bandwidth with our third-party solr server. I’ve tried $query->fields(array(‘nid’)) but I receive the following error.

SearchApiException: Trying to search on field nid which is no indexed fulltext field.

I am using the following code (simplified).

$index = search_api_index_load('my_index');
$query = $index->query();
$query->keys($search_terms);
$query->fields(array('nid')); // doesn't work
$results = $query->execute();
return $results;

How do I get only node IDs from $results?

2 Answers

As @AjitS mentions, if the original node ID is not indexed, then you can't retrieve it from the fields of the search results.

The annoying thing is that the search API knows the IDs, but they're not in an easy to use form. It's happy to give you a list of entity:node/1:en type references, which you can decompose into the original node IDs with something cheesy like this:

  # Converts a list of "entity:node/1:en" type strings to a list of integers
  public function get_nids_from_search_ids($ids) {
    $nids = [];
    foreach($ids as $id) {
      if(substr($id, 0, 12) == 'entity:node/') {
        $rest = substr($id, 12);
        $pieces = explode(':', $rest);
        if($pieces[0] != "") {
          array_push($nids, $pieces[0]);
        }
      }
    }
    return $nids;
  }

It feels like there ought to be a better way without needing to additionally index the node IDs, but it seems there isn't. I guess one day the search API may include convenience methods to get (rigorously) at the "parts" of the IDs it returns.

Answered by Ralph Bolton on October 26, 2021

This is because the fields() method of the SearchAPIQuery class makes the search in fields with datatype fulltext.

In order to get the nid in the result, you have to ensure that its value is being indexed by search_api. You can check that at /admin/config/search/search_api/index/my_index/fields (my_index is the name of the index in this case).

To filter using the nid field you might have to use the condition method instead. The following should work:

$index = search_api_index_load('my_index');
$query = $index->query();
$query->keys($search_terms);
$query->condition('nid', $val); // The third parameter "operator" defaults to "="
$results = $query->execute();
return $results;

Answered by AjitS on October 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP