search mobile facets autocomplete spellcheck crawler rankings weights synonyms analytics engage api customize documentation install setup technology content domains user history info home business cart chart contact email activate analyticsalt analytics autocomplete cart contact content crawling custom documentation domains email engage faceted history info install mobile person querybuilder search setup spellcheck synonyms weights engage_search_term engage_related_content engage_next_results engage_personalized_results engage_recent_results success add arrow-down arrow-left arrow-right arrow-up caret-down caret-left caret-right caret-up check close content conversions-small conversions details edit grid help small-info error live magento minus move photo pin plus preview refresh search settings small-home stat subtract text trash unpin wordpress x alert case_deflection
Swiftype Documentation / api: Searching

Searching

Note: The search-related API endpoints accept both the GET and POST verbs in order to accommodate HTTP clients that do not allow request bodies to be sent with GET requests. If your client will not send a request body on GET, then simply POST the request instead and the API will respond identically.

Search an Engine (across all DocumentTypes)

GET /api/v1/engines/{engine_id}/search.json?q={query}
POST /api/v1/engines/{engine_id}/search.json?q={query}

Search Result Object

Key Value Description
records Hash of document type slug to Array of result objects Contains the search results for each document type.
info Hash of document type slug to a result info object Contains query metadata like number of results and facet counts.
errors Hash of option name to Hash or Array of errors Contains details about query options that were used incorrectly. See Error messages for more details.

Example - Search the books DocumentType for the query "action"
curl -X GET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json?q=action&auth_token=YOUR_API_KEY'
  

Search Options

Option Default Description
page 1 An integer of the page of results you want
per_page 20 An integer of the number of results you want from each page (maximum: 100)
fetch_fields A hash containing arrays of the fields you want to have returned for each object of each DocumentType
highlight_fields A hash containing the fields you want to have highlighted for each object of each DocumentType. For each field, specify size as the maximum number of characters to include in the snippet. Set fallback to true to force inclusion of a non-highlighted snippet if a highlight is not available for that field.
search_fields all text and string fields A hash containing arrays of the fields you want to match your query against for each object of each DocumentType
document_types none (searches all DocumentTypes) An array of DocumentType slug names to search (does not apply to DocumentType scoped search)
functional_boosts none A hash containing boosts that are to be applied to numerically valued fields
filters none A hash specifying additional conditions that should be applied to your query for each DocumentType
precise_expiration none A hash of DocumentType slugs to true or false specifying whether or not filter out expired Documents from the results
sort_field relevance (_score) A hash of DocumentType slug to field name (field must be of type enum, float, integer, or date)
sort_direction desc A hash of DocumentType slug to asc or desc
facets none A hash of DocumentType slug an array of fields to provide result counts for
spelling none A hash of DocumentType slug to strict, always, or retry

Example - Use some of the search options.
curl -X GET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json?q=action&auth_token=YOUR_API_KEY'
  

Example Response

{
  "records": {
    "books": [
      {
        "title": "The Brothers Karamazov",
        "author": "Fyodor Dostoyevsky",
        "price": "14.95"
      },
      ...
    ]
  },
  "info": {
    "books": {
      "query": "brothers",
      "current_page": 1,
      "num_pages": 1,
      "per_page": 20,
      "total_result_count": 18,
      "facets": {}
    }
  },
  "errors": {}
}
Example - Use some of the search options.
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "filters":{"books":{"in_stock":true,"genre":"fiction"}},
        "per_page":5,
        "page":1,
        "fetch_fields":{
          "books":["author","price"]
        },
        "highlight_fields":{
          "books":{"title":{"size":60,"fallback":true}}
        },
        "search_fields":{
          "books":["title"]
        }
      }'
  

Default Search Behavior

When you search an Engine, it will search each DocumentType by default and return a set of matches for each DocumentType in the response. You can search just a single DocumentType by using the search endpoint for that DocumentType.

By default, when you search a DocumentType, the search is performed overall every text field and string field in your schema. That means that if any of your documents contained matching terms in any of those fields, those documents will be returned. If you would rather search specific fields, you pass an array of those fields in the search_fields parameter.

Similarly, any text or string field that matches your query will be returned as part of the result set. If you would rather we only return specific fields, you pass an array of those fields in the fetch_fields parameter.

Snippets and Highlighting

Any fields that are queried during a search will return the top match (if any) in the highlight property of the results. All snippets in this form have HTML entities from the original text encoded. Actual highlighting is specified using (unencoded) <em> tags.

Free-text Query Syntax

Text searches support a basic subset of the standard Lucene query syntax. The supported functions are: double-quoted strings, + and -, AND, OR, and NOT. Visit the Lucene documentation for more details.

Field Weights

At query time you can apply weights to different fields in order to control how each field affects the result rankings. For example, if you want string matches in the title of a book to be weighted more heavily than matches in the author field, you would send a weight on the title field in the search_fields option using the ^(weight) notation.

Query time field weights take precedence over field weights defined in the dashboard.

Example - Return books matching the query "brothers", and weight matches in the title field three times as highly as matches in the author field.
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "search_fields":{
          "books":["title^3","author"]
        }
      }'
  

You may also apply weights to numeric fields by using Functional Boosts.

Filters

Filters allow you to restrict the result set of a query by applying conditions to fields on the matching Documents.

Basic Filtering

The simplest filter requires a field (or set of fields) on each matching Document to be equal to a specified value.

Example - Return books matching the query "brothers" that are in stock and in the fiction genre only.
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "filters":{
          "books":{
            "genre":"fiction",
            "in_stock":true
          }
        }
      }'
  

Filters can also have multiple values. For example, to limit search results to just the "mystery" OR "science fiction" genres, use an array as the value for the filter.

Example - Return books matching the query "brothers" that are in the mystery OR science fiction genres.
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "filters":{
          "books":{
            "genre": ["mystery", "science fiction"]
          }
        }
      }'
  

Filters with AND semantics

By default, if you pass multiple values to a filter (as shown in the previous example), we apply OR semantics to the match. To apply AND semantics, in which case matching Documents must match every value passed to with filter, you may use the AND filter as follows.

Example - Return books matching the query "brothers" that are in both the mystery AND science fiction genres.
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "filters":{
          "books":{
            "genre":{
              "type": "and",
              "values": ["mystery","science fiction"]
            }
          }
        }
      }'
  

Range Queries

Filters also support range queries. You may apply range filters to date, integer, and float fields. If you want the filter unbounded at the low or the high end, just leave off the from or the to parameter.

Example - Return books matching the query "brothers" with a price between $3.00 and $12.00
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "filters":{
          "books":{
            "price":{
              "type": "range",
              "from": 3.00,
              "to": 12.00
            }
          }
        }
      }'
  

Geospatial Queries

You can do geospatial queries by providing latitude and longitude coordinates. Units can be miles (mi) or kilometers (km).

Example - Return books matching the query "brothers" within 5 km of the geographic location (37.75,-122.42)
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "filters":{
          "books":{
            "publisher_location":{
              "type": "distance",
              "max": "5km",
              "lat": 37.75,
              "lon": -122.42
            }
          }
        }
      }'
  

Specifying DocumentTypes

You can search a single DocumentType with the /api/v1/engines/{engine_id}/document_types/{document_type_id}/search end point.

To search multiple DocumentTypes (but not all of them), use the /api/v1/engines/{engine_id}/search end point with the document_types parameter.

Example - Return results matching "brothers" in the magazines and comics DocumentTypes only
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "document_types": ["magazines", "comics"]
      }'
  

Faceting

You can use faceting to give you a count of results for each value of a particular field.

Example - Return the total number of books within each book genre that match your search query
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "facets":{
          "books":["genre"]
        }
      }'
  

Example Response

{
  "records": {
    "books": [
      {
        "title": "The Brothers Karamazov",
        "author": "Fyodor Dostoyevsky",
        "price": "14.95"
      },
      ...
    ]
  },
  "info": {
    "books": {
      "query": "brothers",
      "current_page": 1,
      "num_pages": 1,
      "per_page": 20,
      "total_result_count": 18,
      "facets": {
        "genre": {
           "fiction": 11,
           "non-fiction": 7
        }
      }
    }
  },
  "errors": {}
}

Sorting

By default, results are sorted by relevance (the _score field). The relevance calculation can be affected by weighting fields or applying functional boosts. You can also sort search results by a specific field.

Example - Return the books that match your search query, ordered by price from lowest to highest
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"the",
        "sort_field":{"books":"price"},
        "sort_direction":{"books":"asc"}
      }'
  

Note: Fields used for sorting must be of type enum, float, integer, or date. If you need to sort by a string field, we recommend indexing a second version of that field as an enum and sorting by the enum version.

Spelling

A spelling parameter can be added to your search request. The language used in your spelling correction will match the language of your indexed documents.

There are 3 different spelling options:

Spelling Options Description
strict Returns a spelling correction value when there are no results matching the submitted query
always Returns a possible spelling correction even if there are query matched results
retry Automatically retries the search request with the spelling corrected value if there are no results, but there is a spelling correction

Note: If you are using retry it will be slower because it requires performing a second query.

Example - Return books matching the query "brthers" that are in stock and in the fiction genre only. Adding the spelling parameter will add correct the spelling of "brthers" to "brothers"
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brthers",
        "spelling": "retry"
      }'
  

Functional Boosts

Functional boosts allow you to boost result scores based on the value of an integer or float field.

There are 3 types of functional boosts:

Boost Type Description
logarithmic multiplies the original score by ln(field value)
exponential multiplies the original score by efield value
linear multiplies the original score by field value

Note: We adjust the return value of these functions to ensure the score for a result is not negative or zero.

Example - Return the most popular books first by boosting the total_purchases field, which contains an integer representing the total number of purchases of a book.
curl -XGET 'https://api.swiftype.com/api/v1/engines/bookstore/document_types/books/search.json' \
  -H 'Content-Type: application/json' \
  -d '{
        "auth_token": "YOUR_API_KEY",
        "q":"brothers",
        "functional_boosts":{
          "books":{
            "total_purchases":"logarithmic"
          }
        }
      }'
  

Pagination

Use the per_page and page parameters to paginate results. The info attribute of the result JSON will contain information about the current page and how many pages there are in the results.

Example - Fetching the first page
curl -XGET 'http://swiftype.com/api/v1/engines/bookstore/search.json?q=brothers&auth_token=YOUR_API_KEY'
  

Example Response

{
  "records":{
    "books":[...]
  },
  "info":{
    "books":{
      "query":"title",
      "current_page":1,
      "num_pages":4,
      "per_page":20,
      "total_result_count":76,
      "facets":{
      }
    }
  }
}

Using the current_page, you can advance to the next page:

Example - Advancing to the next page
curl -XGET 'http://swiftype.com/api/v1/engines/bookstore/search.json?q=brothers&page=2&auth_token=YOUR_API_KEY'
  

Example Response

{
  "records":{
    "books":[...]
  },
  "info":{
    "books":{
      "query":"title",
      "current_page":2,
      "num_pages":4,
      "per_page":20,
      "total_result_count":76,
      "facets":{
      }
    }
  }
}

If you advance past the total number of pages, the records attribute will be empty.

Error messages

If there are no problems, the response object will contain an an errors key with an empty object. However, if search options were used incorrectly, these problems will be noted in the errors object.

Example - Errors for limiting DocumentTypes searched to a DocumentType that doesn't exist
{
  "auth_token": "YOUR_API_KEY",
  "q":"brothers",
  "document_types": ["books", "folios"]
}
  

Example Response

{
  "records": {
    "books": [...]
  },
  "info": {...},
  "errors": {
    "document_types": ["DocumentType 'folios' does not exist in this Engine."]
  }
}
Example - Errors for fetching a field that doesn't exist in a DocumentType
{
  "auth_token": "YOUR_API_KEY",
  "q":"brothers",
  "fetch_fields": {"books": ["title", "publisher"]}
}
  

Example Response

{
  "records": {
    "books": [...]
  },
  "info": {...},
  "errors": {
    "fetch_fields": {
      "books": ["DocumentType 'books' does not have a field 'publisher'."]
    }
  }
}
Example - Errors for specifying search fields for a DocumentType that doesn't exist in the Engine
{
  "auth_token": "YOUR_API_KEY",
  "q":"brothers",
  "search_fields": {"folios": ["title"]}
}
  

Example Response

{
  "records": {
    "books": [...]
  },
  "info": {...},
  "errors": {
    "search_fields": {
      "folios": ["DocumentType 'folios' does not exist in this Engine."]
    }
  }
}
Example - Errors for specifying search fields for a DocumentType that exists in the Engine but is excluded
{
  "auth_token": "YOUR_API_KEY",
  "q":"brothers",
  "search_fields": {"magazines": ["title"]},
  "document_types": ["books"]
}
  

Example Response

{
  "records": {
    "books": [...]
  },
  "info": {...},
  "errors": {
    "search_fields": {
      "magazines": ["DocumentType 'magazines' exists in this Engine but is not included in the list of document types to search."]
    }
  }
}
Example - Errors for sorting on an unsortable field
{
  "auth_token": "YOUR_API_KEY",
  "q":"brothers",
  "sort_field": {"books": "title"}
}
  

Example Response

{
  "records": {
    "books": [...]
  },
  "info": {...},
  "errors": {
    "sort_field": {
      "books": ["Cannot sort by 'title'. Only enum, numeric, and date fields can be sorted."]
    }
  }
}