java
46 lines · 8 steps
Rebuilding a search index at Spring startup
An ApplicationRunner streams every active product and writes it into a search view in fixed-size batches when the app boots.
Explained by
highlit
1@Component
2@Order(20)
3public class ProductSearchIndexRunner implements ApplicationRunner {
4
5 private static final Logger log = LoggerFactory.getLogger(ProductSearchIndexRunner.class);
6
7 private final ProductRepository products;
8 private final ProductSearchView searchView;
9
10 public ProductSearchIndexRunner(ProductRepository products, ProductSearchView searchView) {
11 this.products = products;
12 this.searchView = searchView;
13 }
14
15 @Override
16 public void run(ApplicationArguments args) {
17 if (args.containsOption("skip-index")) {
18 log.info("Skipping product search index rebuild (--skip-index present)");
19 return;
20 }
21
22 StopWatch watch = new StopWatch();
23 watch.start();
24 searchView.clear();
25
26 int indexed = 0;
27 try (Stream<Product> stream = products.streamAllActive()) {
28 List<ProductDocument> batch = new ArrayList<>(500);
29 for (Product product : (Iterable<Product>) stream::iterator) {
30 batch.add(ProductDocument.from(product));
31 if (batch.size() == 500) {
32 searchView.saveAll(batch);
33 indexed += batch.size();
34 batch.clear();
35 }
36 }
37 if (!batch.isEmpty()) {
38 searchView.saveAll(batch);
39 indexed += batch.size();
40 }
41 }
42
43 watch.stop();
44 log.info("Rebuilt product search index: {} documents in {} ms", indexed, watch.getTotalTimeMillis());
45 }
46}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1ApplicationRunner lets you run one-off work after the context is ready, ordered against other runners.
- 2Streaming rows and flushing in fixed-size batches keeps memory flat over large datasets.
- 3A command-line flag gives operators an escape hatch to skip expensive startup work.
Related explainers
java
public final class FileChecksum { private static final char[] HEX = "0123456789abcdef".toCharArray();
Streaming a SHA-256 file checksum in Java
hashing
streams
resource-management
Intermediate
7 steps
typescript
import { Injectable, signal, computed } from '@angular/core'; import { HttpInterceptorFn, HttpContextToken,
Tracking HTTP loading state in Angular
signals
http-interceptor
reference-counting
Intermediate
8 steps
javascript
const express = require('express'); const compression = require('compression'); const zlib = require('zlib');
Tuning Express response compression
compression
middleware
http
Intermediate
9 steps
python
from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel, ConfigDict, EmailStr from sqlalchemy.orm import Session
Building a users router in FastAPI
routing
serialization
dependency-injection
Intermediate
7 steps
typescript
type Event = Record<string, unknown>; interface BatcherOptions { endpoint: string;
Batching analytics events in TypeScript
batching
buffering
async
Intermediate
8 steps
java
@Service public class OrderCheckoutService { private final OrderRepository orderRepository;
How @Transactional guards a Spring checkout
dependency-injection
transactions
atomicity
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/rebuilding-a-search-index-at-spring-startup-explained-java-4cf4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.