|
<?php |
|
/** |
|
* @file |
|
* |
|
* Sample query using Drupal's Apache Solr Search module's API. |
|
* |
|
* Given a loaded node, it searches for related content in Solr. |
|
*/ |
|
|
|
$node = node_load(383871); |
|
|
|
// Build the content types filter. |
|
$content_types = array('article'); |
|
$content_type_filter = new SolrFilterSubQuery('OR'); |
|
foreach ($content_types as $content_type) { |
|
$content_type_filter->addFilter('bundle', $content_type); |
|
} |
|
|
|
/// Build the Issues filter. |
|
$issues = array(); |
|
if ($items = field_get_items('node', $node, 'field_issues')) { |
|
foreach ($items as $issue) { |
|
$issues[] = 'node:' . $issue['target_id']; |
|
} |
|
} |
|
$issues_filter = new SolrFilterSubQuery('OR'); |
|
foreach ($issues as $issue) { |
|
$issues_filter->addFilter('sm_field_issues', $issue); |
|
} |
|
|
|
// Build the Topics filter. |
|
$topics = array(); |
|
if ($items = field_get_items('node', $node, 'field_topics')) { |
|
foreach ($items as $topic) { |
|
$topics[] = 'node:' . $topic['target_id']; |
|
} |
|
} |
|
$topics_filter = new SolrFilterSubQuery('OR'); |
|
foreach ($topics as $topic) { |
|
$topics_filter->addFilter('sm_field_topics', $topic); |
|
} |
|
|
|
// Group conditions together. |
|
$main_filter = new SolrFilterSubQuery('AND'); |
|
$main_filter->addFilterSubQuery($content_type_filter); |
|
$issues_or_topics = new SolrFilterSubQuery('OR'); |
|
$issues_or_topics->addFilterSubQuery($issues_filter); |
|
$issues_or_topics->addFilterSubQuery($topics_filter); |
|
$main_filter->addFilterSubQuery($issues_or_topics); |
|
|
|
// Create the query object and perform the request. |
|
try { |
|
// Create the query and then configure it. |
|
$query = apachesolr_drupal_query('apachesolr'); |
|
|
|
// Specify that we only want nids in the result. |
|
$query->addParam('fl', 'entity_id'); |
|
// Only return 4 matches. |
|
$query->addParam('rows', 4); |
|
// Add the above filters. |
|
$query->addFilterSubQuery($main_filter); |
|
// Sort by publish date in descending order. |
|
$sort_field = 'ds_field_publish_date_sort'; |
|
$sort_direction = 'desc'; |
|
$query->setAvailableSort($sort_field, $sort_direction); |
|
$query->setSolrsort($sort_field, $sort_direction); |
|
|
|
// Run query and render results if matches are found. |
|
list($final_query, $response) = apachesolr_do_query($query); |
|
if ($response->code == '200' && $response->response->numFound > 0) { |
|
// Extract nids from the response and load them. |
|
$nids = array(); |
|
foreach ($response->response->docs as $result) { |
|
$nids[] = $result->entity_id; |
|
} |
|
$nodes = node_load_multiple($nids); |
|
if (count($nodes)) { |
|
// Build and return the list of rendered teasers. |
|
return theme('my_theme_callback', array('nodes' => $nodes)); |
|
} |
|
} |
|
} |
|
catch (Exception $e) { |
|
watchdog('mymodulename', 'There was an error while processing More Like This block: %error', array('%error' => $e->getMessage()), WATCHDOG_ERROR); |
|
} |