· 3 min read

Effectively query Solr using Next.js

Apache Solr provides a flexible and powerful search platform

Apache Solr provides a flexible and powerful search platform

Apache Solr is a powerful search platform that provides robust full-text search capabilities. In this article, I will explore how to effectively query Solr using Next.js, with practical code examples from a real-world implementation.

Basic Query Structure

The fundamental way to query Solr is through its REST API. Here’s a basic example of how to structure a Solr query URL:

const SOLR_BASE_URL = `${process.env.SOLR_HOST}/solr/${process.env.SOLR_CORE}`;
const solrUrl = `${SOLR_BASE_URL}/select?q=${encodeURIComponent(query)}`;

Query Parameters

Solr supports various query parameters that help you fine-tune your search. Here are the key parameters commonly used:

  • q: The main query string
  • start: Starting position for pagination
  • rows: Number of results to return
  • sort: Field and direction for sorting results
  • sow: Split on whitespace (true/false)

Advanced Query Techniques

Wildcard Searches

One common technique is to use wildcards to match partial terms. Here’s how to implement a wildcard search:

const terms = query
  .split(' ')
  .map((term) => `*${term}*`)
  .join(' AND ');

This transforms a search like “hello world” into “hello AND world”, matching these terms anywhere in the field.

Field Boosting

You can boost certain fields to give them higher relevance in the search results:

const queryWithBoost = `((title:(${terms}))^2 OR content:(${terms}))`;

In this example, matches in the title field are given twice the weight (^2) compared to matches in the content field.

Filtering Results

Solr queries can include multiple components combined with logical operators. Here’s how to add filters to your query:

const queryComponents = [];

// Add main search terms
if (query !== '*:*') {
  queryComponents.push(`((title:(${terms}))^2 OR content:(${terms}))`);
}

// Add tag filter
if (tag) {
  queryComponents.push(`tags:"${tag}"`);
}

// Add boolean filter
if (showFavorites) {
  queryComponents.push('is_fave:true');
}

// Combine all components
const combinedQuery = queryComponents.length > 0 ? queryComponents.join(' AND ') : '*:*';

Making the Request

Here’s a complete example of how to make a Solr query using fetch:

const solrUrl = `${SOLR_BASE_URL}/select?indent=false&q=${encodeURIComponent(
  combinedQuery
)}&sow=${splitOnWhitespace}&start=${start}&rows=${rows}${sort ? `&sort=${encodeURIComponent(sort)}` : ''}`;

try {
  const response = await fetch(solrUrl, { cache: 'no-store' });
  if (!response.ok) {
    throw new Error('Failed to fetch from Solr');
  }
  const data = await response.json();
  return data;
} catch (error) {
  console.error('Error querying Solr:', error);
  throw new Error('Failed to fetch results');
}

Document Updates

Solr also supports atomic updates to modify specific fields without replacing the entire document:

interface SolrAtomicUpdate {
  set: string | number | boolean | string[] | boolean[];
}

// Example update
const updateDoc = {
  id: documentId,
  title: { set: newTitle },
  tags: { set: newTags },
  updated_at: { set: new Date().toISOString() },
};

await fetch(`${SOLR_BASE_URL}/update?softCommit=true`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify([updateDoc]),
});

Best Practices

  1. Always encode query parameters to handle special characters
  2. Use softCommit=true for updates that don’t need immediate durability
  3. Implement error handling and logging for production environments
  4. Consider caching strategies based on your use case
  5. Use field boosting to improve result relevance

Conclusion

Apache Solr provides a flexible and powerful search platform that can be easily integrated with Next.js applications. By understanding these querying techniques and best practices, you can build robust search functionality that scales with your needs.

Remember to consult the official Solr documentation for more advanced features and optimizations.

Back to Posts

Related Posts

View All Posts »