Search as a projection: why Elasticsearch should not be the only article store

Separate primary MySQL/InnoDB records from a search projection: allowlisted fields, current cards, and rebuilding an index from articles.

A derived representation can be rebuilt while its original source is preserved.

Imagine a journal where search already finds articles and an editor withdraws one of them. The search index still contains its old title and summary. If the page builds a card directly from the Elasticsearch response, the withdrawn article may remain visible. Losing the index raises another question: where can the text, publication state, and link to the language version be recovered from?

For this journal, define a primary article store and a separate search projection. The former owns the current record; the latter helps locate it. This is an application design choice rather than a claim that Elasticsearch cannot store documents. Continue one article_demo on Symfony 8.1 and PHP 8.4+; the search module uses a separate disposable Elasticsearch 9.4.3 node and its own temporary MySQL 8.4 schema through native PDO.

Which record can be recovered without search

The primary MySQL/InnoDB table stores an identifier, site, locale, state, revision, title, summary, full body, and editorial note. The identifier and revision use BIGINT; site, locale, and state use VARCHAR with utf8mb4_0900_bin collation, while the text fields, including the title, use LONGTEXT. A CHECK restricts the state to draft or published. A public card can be read by identifier without contacting the search service. Saving editorial changes and opening a known article therefore do not depend on the index being ready.

Elasticsearch receives only the data needed for search and a reference back to the source. The _source field stores the JSON document submitted to the index; it does not know which additional fields, history, or rules remained in the editorial store. This follows from its documented semantics. When the index receives a reduced projection, having _source does not make it a complete article backup.

Establish this separation before the first indexing operation. In the example, revision is the primary record's revision. It can help reveal lag, but it does not by itself order messages, prevent a late older write, or create a transaction across stores. Those guarantees require a separate protocol.

Define backups of the primary database separately. Being able to rebuild an index helps only while the source records still exist and can be read. Losing the primary MySQL data is a different event with a different recovery procedure. The laboratory does not substitute a search check for that procedure or establish that a primary-data backup exists. This experiment's temporary schema is not intended to hold real editorial material.

A projection starts with an allowlist of fields

The document builder takes only published records and explicitly selects 6 fields. It does not serialize the whole database row or an object with arbitrary properties. The document for the first synthetic article looks like this:

{
  "article_id": 1,
  "site": "journal",
  "locale": "uk",
  "revision": 1,
  "title": "Cache keys",
  "summary": "Choosing cache keys"
}
Data Primary record Search document
Identifier, site, locale, revision Stored Copied for matching and selection
Title and summary Current values Derived text fields for search
Publication state Determines availability Only published records enter the build
Full body and editorial note Stored under product rules Not transmitted

In the mapping, the identifier and revision use long, the site and locale use keyword, and the title and summary use text. The dynamic: strict setting helps expose an uncoordinated field addition. The mapping is supplied when creating a new index. This is an additional schema check; the decision not to send the editorial note must already be made in the projection function.

The example does not search inside the full body. If that becomes necessary, add a derived text field deliberately, with rules for removing internal fragments, language analysis, and a corresponding availability check. Adding a field changes both search usefulness and the amount of data that must be removed after publication is withdrawn.

A matching document is not yet a finished card

The search request filters by site and locale, searches the title and summary, and returns at most 20 candidates. _source: false removes the document text from the response. The Search API describes this option and rejection of partial results through allow_partial_search_results=false. After receiving the response, the adapter also checks for timeouts, shard failures, and valid identifier shapes.

Cards are built through a second read from the primary database. One parameterized query checks the site, locale, and published state again; parameters are not interpolated as SQL text. A list of identifiers requires a separate placeholder for every value, as explained by PDO::prepare. The application then preserves candidate order while skipping records that can no longer be displayed:

<?php

declare(strict_types=1);

namespace App\SearchProjection;

final class Search
{
    public function __construct(
        private readonly PrimaryStore $primary,
        private readonly ElasticsearchProjection $projection,
        private readonly string $index,
    ) {
    }

    public function find(string $site, string $locale, string $query): array
    {
        $ids = $this->projection->candidateIds($this->index, $site, $locale, $query);
        $current = $this->primary->publishedCards($ids, $site, $locale);
        $cards = [];
        foreach ($ids as $id) {
            if (isset($current[$id])) {
                $cards[] = $current[$id];
            }
        }
        return $cards;
    }
}

If the title changed, the card receives the new title. If the record was deleted or withdrawn, there is no card. The old search document can still affect the match and ranking, however: the new title may no longer contain the query term. Reading the primary record again neither refreshes the index nor adds missing new articles.

There may consequently be fewer cards than the limit. The example does not fetch another page of candidates or report the total number of search matches as the number of available articles. It is also not a complete authorization system: nonpublic content needs additional current access rules. The state check applies at the database read, not throughout the response's subsequent lifetime.

A missing index and an empty response mean different things

A healthy search can return an empty list. A missing index, transport error, or incomplete response means something else: the search capability is currently unavailable. The teaching code raises ProjectionUnavailable for these conditions. It does not replace them with a message saying no matching articles exist.

If the primary database cannot be read after candidates arrive, that error also propagates. The adapter does not silently fall back to an old _source. Otherwise an ordinary storage failure would change display rules and return text whose publication had already been withdrawn. Rendering an error, retrying, and keeping a direct article route available are interface decisions outside this console laboratory.

Rebuilding reads the primary records

For this small setup, data changes stop during the build. One SELECT materializes the current published records, and a new index is then created with a separate exact name. Documents are written sequentially. Only after a successful refresh does the build return an index name that can be passed to a new reader.

A refresh makes recent operations available to search. It is separate from the durability of the primary database; the Refresh API documentation also explains its resource cost. In the small experiment, an explicit refresh marks the boundary of a completed build. This does not imply a recommendation to refresh after every editorial change.

An interruption after some writes must not return a completed index. A laboratory hook throws an exception after the first actual write, and the builder removes the incomplete index it created. The previous completed index remains separate. This exercises an ordinary exception; an abruptly terminated process needs a different mechanism to clean up leftovers.

There is a relevant distinction: the Elasticsearch Reindex API copies documents from an existing search source into another index. It will not read our MySQL database or recover fields that never entered the projection. In this example, rebuilding after index loss is the responsibility of the application's builder.

What rebuilding during active writes would require

Allow editorial writes during a long rebuild, and the copy may already be stale before it finishes. A production design must define a consistent starting view, a way to catch up with changes, ordering for updates and deletions, and the point at which reads switch over. Merely renaming an index does not solve these problems.

This setup implements neither an alias, a change queue, an outbox, nor recovery after power loss. It demonstrates a narrower contract: a completed index can be rebuilt from a quiescent primary dataset. A repeated build uses a new name and should reproduce the same available cards. An empty primary dataset is also a valid outcome when the index actually exists and search works.

Which behavior to exercise in your own setup

The laboratory contains 12 sequential scenario groups for a separate Elasticsearch 9.4.3 node and a MySQL 8.4 primary store: allowlisted projection fields, site/locale, current title, withdrawal/deletion, index loss, rebuild/repeat, controlled interruption, an unavailable primary store, an empty dataset, and foreign-index rejection. Primary-store checks also cover case-sensitive site and locale matching, rollback of a title change, and reading a committed change through another native connection to the same schema.

These groups combine real HTTP requests to Elasticsearch with native SQL queries to MySQL; they are not a PHPUnit test count. The primary-store failure scenario uses a separate temporary schema without an articles table: the PDO error must propagate rather than return an old _source. Separate shared SearchLab tests check local guards and transport but do not replace a run against the search server.

Add src/SearchProjection, shared src/SearchLab, and ProjectionLabCommand to the same application. The dependencies are symfony/http-client:8.1.* and the PDO_MYSQL driver; emulated prepares are disabled. Shared App\Infrastructure\MysqlLab creates an owned temporary schema and separate migrator and runtime DML connections. An explicit initialize call first creates the table through the migrator with no active transactions, then inserts synthetic data in a separate transaction. MySQL DDL can cause an implicit commit: this is neither an atomic schema upgrade nor an automatic data transfer from the old SQLite database. The constructor performs no DDL; the runtime account has no CREATE, ALTER, or DROP privileges. Preserve the existing Notes database. The entries below supplement the existing services block; do not automatically scan DTOs, index adapters, or the Lab runner as services.

composer require symfony/http-client:'8.1.*'
services:
    App\Command\ProjectionLabCommand: ~

The prerequisite is your own disposable local Elasticsearch 9.4.3 node rather than an existing cluster. Configure single-node mode, a random cluster nonce, a loopback-only HTTP port, no host data mounts, and disabled index auto-creation. This local experiment does not model security/TLS; the node is unsuitable for a shared or remote host.

Shared LocalElasticsearch accepts only the exact origin http://127.0.0.1:PORT, checks cluster.name/version, and validates the index nonce. Redirects are disabled; idle timeout is 5s, total duration is bounded at 15s, and streaming response reads are capped at 1 MiB. Operations require exact indices created by that object. Loopback and a nonce guard against an accidental foreign target without authenticating local users.

cluster.name must be projection_lab_<16 lowercase hex>; the module creates exact index names with that prefix.

SEARCH_WORKSPACE="$(mktemp -d)"
bash fixtures/mysql_labs/run.sh php bin/console app:projection-lab "$SEARCH_WORKSPACE/projection" \
  --url="$SEARCH_LAB_URL" --cluster="$SEARCH_LAB_CLUSTER"

The URL and cluster identity in the command must come from your own disposable Elasticsearch node launcher. Never substitute another service. For MySQL, run the command through the previously introduced guarded wrapper fixtures/mysql_labs/run.sh; it supplies the disposable-server configuration to shared MysqlLab. The command reserves a new absolute directory under a trusted canonical parent; existing files, directories, and symlinks are rejected. It writes report.json without overwriting. Primary records live in a separate temporary MySQL schema, not a file in that directory; the laboratory removes its owned schema when closed. Repeating the exercise needs another new directory.

Only the launcher owner removes its container after verifying its exact ID/label. The commands perform no global Docker cleanup, delete no foreign indices, and configure no production TLS or roles.

The practical design follows one requirement: losing the search projection must leave the articles and their display rules intact. If rebuilding depends on the only copy in the lost index, the boundary between the source of truth and derived data has not yet been established.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

  1. Data & Infrastructure An article has been withdrawn: how to remove it from search
  2. Databases The article was saved but the event was not sent: why use a transactional outbox
  3. Data & Infrastructure Rebuilding a search index without mixing old and new schemas