Application integration | laravel-site-search-rust | Spatie       

 SPATIE  

laravel-site-search-rust
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-site-search-rust](https://spatie.be/docs/laravel-site-search-rust/v1)  Application integration

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-site-search-rust/v1) 

  Application integration    
- [ Introduction ](https://spatie.be/docs/laravel-site-search-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-site-search-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-site-search-rust/v1/installation-and-setup)
- [ Application integration ](https://spatie.be/docs/laravel-site-search-rust/v1/application-integration)
- [ Usage ](https://spatie.be/docs/laravel-site-search-rust/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-site-search-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-site-search-rust/v1/changelog)

 Application integration
=======================

###  On this page 

1. [ Provider and configuration ](#content-provider-and-configuration)
2. [ Keep an application's crawl command ](#content-keep-an-applications-crawl-command)
3. [ Saved indexes ](#content-saved-indexes)
4. [ Profiles and indexers ](#content-profiles-and-indexers)
5. [ Native jobs ](#content-native-jobs)
6. [ Events and results ](#content-events-and-results)
7. [ Handle failures ](#content-handle-failures)

Provider and configuration
--------------------------------------------------------------------------------------------------------------------------------------

Register `spatie_site_search::service_provider()` with the application's native provider collection. It uses package-tools to register configuration, migrations and commands. Boot never crawls a site or runs migrations.

The typed `spatie_site_search::Config` section provides:

- `default_driver`: `database`, `array` or `meilisearch`; environment key `SITE_SEARCH_DRIVER`.
- `default_profile`: a registered profile name; environment key `SITE_SEARCH_PROFILE`.
- `default_indexer`: an `Arc<dyn Indexer>` used unless a profile selects another extractor.
- `ignore_content_on_urls`: additional path globs that skip content but preserve link discovery.
- `do_not_crawl_urls`: additional path globs that block requests.
- `ignore_content_by_css_selector`: additional excluded HTML subtrees.
- `do_not_index_content_headers`: additional response-header names that suppress indexing.
- `queue` and `queue_connection`: optional native dispatch overrides, from `SITE_SEARCH_QUEUE` and `SITE_SEARCH_QUEUE_CONNECTION`.
- `register_crawl_command`: defaults to `true`; set to `false` if your application owns `site-search:crawl`.

Without queue overrides, each selected job keeps its own native options. A shared cache store is required for crawl locks across multiple worker processes. The lock lasts one hour; the default job timeout is 35 minutes and the crawler limit is 30 minutes. Custom jobs must keep their runtime below the lock lifetime.

Keep an application's crawl command
---------------------------------------------------------------------------------------------------------------------------------------------------------------

- Command names come from native clap definitions, not runtime configuration.
- Disable only the package's crawl command when the application already has one. Other commands, migrations, jobs and services remain registered.
- Call `SearchManager::crawl(id)` or dispatch `CrawlSiteJob::from(id)` from the application command. A custom command can also use a different clap name.

```
use spatie_site_search::{Config, service_provider};

let app = laravel::Application::configure()
    .with_providers(|providers| { providers.add(service_provider()); })
    .with_config(|config, _| {
        config.section_mut::<Config>().register_crawl_command = false;
    })
    .create();
```

Saved indexes
-----------------------------------------------------------------------------------------------

After running application migrations, save an index with the model or create-index command:

```
use laravel::model::update;
use spatie_site_search::models::SiteSearchConfig;

let mut index = SiteSearchConfig::create_index("docs", "https://example.test/docs").await?;
update!(index {
    driver: Some("meilisearch"),
    extra: r#"{"meilisearch":{"url":"http://127.0.0.1:7700","indexSettings":{"filterableAttributes":["extra.category"]}}}"#
}).await?;
```

The native model stores the URL, enabled state, optional driver/profile names, backend options, indexed/discovered/failed counts, start/end timestamps and completion diagnostic. Jobs serialize its ID and reload the current row when executed. The crawl command selects only enabled rows; direct manager calls can explicitly crawl a disabled row.

For database indexes, `extra` can contain `{"database":{"connection":"search","fullText":true}}` to select a configured framework connection and native full-text mode. Migrate that connection's search storage explicitly with `DatabaseDriver::migrate()` before using it. Saved configurations remain on the application's default model connection.

Direct callers can select `DatabaseDriver::new(connection).full_text()` through `SiteSearch::with_driver`. Full-text mode uses SQLite FTS5 with Porter stemming, MySQL/MariaDB FULLTEXT, or PostgreSQL tsvector with English stemming and no stop-word removal. All support prefixes and blank-query browsing. MySQL uses its native boolean-mode word/stop-word rules; SQLite and PostgreSQL require every query token. Ranking is backend-specific. Punctuation is tokenized and values are bound, not interpolated into SQL.

For Meilisearch, use `extra.meilisearch.url`, optional `apiKey`, and optional `indexSettings`. Do not commit API keys or print the saved backend options. Prefer environment-provided values when saving them. The array backend lives for the lifetime of the manager and is intended for tests, not separate web and queue processes.

Profiles and indexers
-----------------------------------------------------------------------------------------------------------------------

Profiles can independently customize crawling, indexing, extraction and crawler options. Register names by replacing the native `Profiles` binding:

```
use spatie_site_search::{Profiles, profiles::SearchProfile};

struct DocsProfile;
impl SearchProfile for DocsProfile {
    fn should_crawl(&self, url: &url::Url) -> bool {
        !url.path().starts_with("/docs/internal")
    }
    fn should_index(&self, page: &spatie_crawler::Page) -> bool {
        page.url.path() != "/docs/archive"
    }
}

let app = laravel::Application::configure()
    .with_providers(|providers| { providers.add(spatie_site_search::service_provider()); })
    .with_services(|services| {
        let mut profiles = Profiles::default();
        profiles.add("docs", DocsProfile);
        services.instance(profiles);
    })
    .create();
```

Set a saved row's `profile` to `docs`, or select it as `Config.default_profile`. Override `SearchProfile::document` to select a different indexer per page, add metadata, change URLs or skip a response. Override `configure_crawler` for concurrency, timeouts, renderers or other crawler settings. Mandatory same-origin/subtree restrictions still apply after this hook.

Implement `Indexer` for custom extraction and assign it to `Config.default_indexer`, or call it from a profile. `DefaultIndexer` extracts cleaned body text, title, H1, description and heading-anchored entries. It excludes configured subtrees and filters short, path-like and JSON-like entries. A custom indexer can fill `date_modified_timestamp` and `extra`; the default does not invent a modification date.

Native jobs
-----------------------------------------------------------------------------------------

Replace the default job through a generic provider, without replacing the framework queue:

```
use laravel::{container::Inject, queue::{self, Queueable}};
use spatie_site_search::SearchManager;

#[derive(Debug, Queueable)]
struct CrawlDocs { id: i64 }

impl From<i64> for CrawlDocs {
    fn from(id: i64) -> Self { Self { id } }
}

#[queue::job(queue = "search", tries = 2, timeout = 35.minutes())]
impl CrawlDocs {
    async fn handle(self, search: Inject<SearchManager>) -> laravel::Result<()> {
        search.crawl(self.id).await?;
        Ok(())
    }
}

let app = laravel::Application::configure()
    .with_providers(|providers| {
        providers.add(spatie_site_search::service_provider_with_job::<CrawlDocs>());
    })
    .create();
```

Both queued and `--sync` commands use the selected job. Native queue serialization, options, workers, dependency injection and fakes remain in control. The default saved model is concrete; applications can keep their own model alongside it and dispatch its saved config ID, or use `SiteSearch::with_driver` directly for a different persistence lifecycle.

Events and results
--------------------------------------------------------------------------------------------------------------

Managed crawls dispatch native events:

- `IndexingStarted` before crawling.
- `IndexedUrl` for each extracted response, with the response, discovery source and progress.
- `FailedToCrawlUrl` with the URL, error, linking URL and progress.
- `CrawlFinished` after crawling, with the finish reason and counters, before replacement.
- `NewIndexCreated` when the logical index becomes searchable with the new contents.
- `IndexingEnded` after successful replacement.

Use native event listeners or `laravel::event::fake()` in tests. Direct crawls are event-free unless called through `crawl_with_events`. Listener errors propagate: a listener failing after storage replacement cannot undo that replacement.

`SearchManager::search` resolves the saved driver and returns `SearchResults` with hits, total count, limit and offset. `SiteSearch::search` supports the same result window for explicit drivers. Database search defaults to the existing exact-token ranking unless full-text mode is selected. The array driver uses exact tokens. Meilisearch uses its own query grammar and accepts backend search parameters. Its reported total is an estimate.

Drivers expose atomic bulk replacement, deletion, listing, count and processing status. Database replacement is transactional. Meilisearch builds a staging index, waits for tasks and swaps it into place. A network failure while a remote swap is completing has an indeterminate outcome: inspect the remote index before retrying. Cleanup failures are logged and may leave a staging index to remove.

Handle failures
-----------------------------------------------------------------------------------------------------

- Match `Error` variants instead of parsing messages. The enum is non-exhaustive, so include a fallback arm.
- `IncompleteCrawl` retains its counters through managed crawls. The saved model records the failed attempt while the previous index stays searchable.
- `AlreadyCrawling(id)` means another worker holds the crawl lock. No second crawl starts.
- `Framework(error)` retains the native error, including database and event-listener failures. Use its `downcast_ref` or `chain` methods to inspect causes.
- URL, glob, JSON, HTTP, pagination and timeout variants retain their source errors. CSS selector diagnostics are owned because the parser error borrows its input.

```
use spatie_site_search::{Error, SearchConfig};

match SearchConfig::new("file:///private/site") {
    Err(Error::InvalidSiteUrl) => println!("Choose an HTTP(S) URL."),
    Err(error) => return Err(error),
    Ok(_) => unreachable!("the example URL is not HTTP(S)"),
}
```

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
