Usage | 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)  Usage

 Version   v1      

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

  Usage    
- [ 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)

 Usage
=====

###  On this page 

1. [ Configure a crawl ](#content-configure-a-crawl)
2. [ Use a framework connection ](#content-use-a-framework-connection)
3. [ Command line ](#content-command-line)
4. [ Integrate URL hits with posts ](#content-integrate-url-hits-with-posts)

Configure a crawl
-----------------------------------------------------------------------------------------------------------

```
use spatie_site_search::SearchConfig;

let config = SearchConfig::new("https://your-site.example")?
    .ignore_urls(["/", "/rss", "/search", "/originals*", "/community*",
        "/newsletter", "/archive*", "/tags*"])?
    .ignore_selectors([".advertisement"])?
    .no_index_headers(["x-private-content"])?
    .do_not_crawl(["/login", "/logout", "/admin*"])?
    .exclude_query_keys(["preview"])
    .strip_title_suffixes([" - My blog"]);
```

- URL globs match the encoded path, without a query. `*` can cross path separators.
- Ignoring content does not stop link discovery from that page.
- Selector exclusions remove whole subtrees from title/body text but do not hide their links from the crawler.
- Defaults exclude `nav`, `footer`, `script`, `style`, `template`, and `[data-no-index]`.
- The presence of `site-search-do-not-index` suppresses indexing even if its value is empty or `false`.
- Additional header names are case-insensitive.
- Standard robots meta and `X-Robots-Tag: noindex` also suppress indexing.
- Query exclusions inspect decoded, case-insensitive keys. `?sort=asc&page=2`, `?%70age=2`, and `?UTM_source=mail` are excluded. `?notpage=2` and `?value=utm_source` are not.
- Remaining query keys are sorted and encoded without losing values. Repeated values retain their original order because a server may use the first or last value.
- `?q=a%2Bb` and `?q=a+b` remain distinct. The package does not strip all query strings and merge distinct pages.

Use a framework connection
--------------------------------------------------------------------------------------------------------------------------------------

```
use std::time::Duration;
use spatie_site_search::{SearchConfig, SiteSearch};

let search = SiteSearch::new(laravel::db::default_connection()?, "blog")?;
search.migrate().await?;
let config = SearchConfig::new("https://your-site.example")?;
let indexed = search.crawl(config, |crawler| {
    crawler.user_agent("my site search crawler")
        .concurrency(1)
        .delay(Duration::from_millis(100))
        .time_limit(Duration::from_secs(1800))
}).await?;

let hits = search.query("rust database", 40).await?;
for hit in hits {
    println!("{} {}", hit.score, hit.url);
}
```

- The callback takes `spatie_crawler::CrawlerBuilder`. Configure timeouts, request headers, throttling, fetchers and JavaScript renderers there.
- Server-rendered HTML needs no browser. JavaScript-only sites require a crawler renderer and its browser/service prerequisites.

The package applies same-origin, path-subtree, do-not-crawl and HTML MIME rules after the callback. These replace the builder's URL policy and cannot be loosened through it. `/docs` includes `/docs/child` but not `/docs-other`. Redirect destinations must pass those rules too. With the default HTTP fetcher, private-network requests are blocked. Explicitly configure `HttpFetcher::builder().allow_private_networks(true)` only for a trusted local site. Custom fetchers/renderers carry their own network safety responsibilities.

- Run one crawl per index at a time. Managed crawls acquire a native cache lock; direct callers coordinate their own crawls.
- Pages are staged in memory. Database replacement runs in a transaction after a complete, failure-free crawl.
- Default bounds are 10,000 requests and 30 minutes. Reaching either returns an error instead of committing a partial index.
- Successful refreshes remove stale and newly archived pages. Cancellation, request failure and transaction errors preserve the old index.
- Different index names share tables but not results.
- Exact-token database and in-memory queries accept up to 32 distinct lowercase Unicode alphanumeric tokens, all required.
- Punctuation separates tokens; it is not SQL or full-text syntax. Text is HTML-decoded before tokenization.
- Title occurrences contribute 8 points; body and description occurrences contribute 1 point. Each field counts at most 10 occurrences per token.
- Higher scores sort first and URL breaks ties. Empty queries, punctuation-only queries and a zero limit return no hits.
- Exact-token search does not stem, match prefixes or fold accents.

Those are the default exact-token rules. Select `DatabaseDriver::full_text()` or the saved `database.fullText` option for native database prefixes, stemming and blank-query browsing. See [application integration](application-integration) for backend-specific behavior.

Command line
--------------------------------------------------------------------------------------------

Set `SITE_SEARCH_DATABASE_URL` to a disposable or application-owned database URL. Do not pass credentials through shell history. For example, an SQLite URL is `sqlite://storage/search.sqlite?mode=rwc`.

```
cargo run --locked -- --index blog crawl https://your-site.example \
    --ignore-url '/' --ignore-url '/archive*' --ignore-url '/search' \
    --ignore-selector '.advertisement' --do-not-crawl '/admin*'
cargo run --locked -- --index blog query 'rust database' --limit 40
```

The standalone `spatie-site-search` binary retains these connection-only commands. `crawl` creates the search storage tables if needed. `query` does not change the database. Each result prints `score`, a tab, and the URL. Use `--allow-private-networks` only for a disposable local site. CLI failures exit nonzero. For saved indexes and native queued jobs, use the [application integration](application-integration).

Integrate URL hits with posts
-----------------------------------------------------------------------------------------------------------------------------------------------

- `Hit` exposes `id`, `document` and `score`. Document fields such as `url`, `title`, `content`, `h1`, `description`, `entries`, `extra` and `date_modified_timestamp` are also accessible through dereferencing.
- `title()` falls back to H1.
- `url_with_anchor(query)` links to a matching section.
- `highlighted_snippet(query, max_words)` returns escaped text with package-generated `<em>` markup.

The database index returns one result per canonical URL. It does not depend on your application models. Extract numeric post IDs from URL paths, retain the first hit per post ID, and load posts in that order. A URL hit's ID is a SHA-256 hash scoped to its index, not a post primary key. The requested hit limit applies before this application-specific filtering.

Call `search(query, limit, offset, parameters)` for a result window with `total_count`, `limit`, and `offset`. Database and in-memory drivers reject non-empty backend parameters. Meilisearch forwards them, while explicit query, limit and offset arguments take precedence.

 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)
