Search parameters
Search parameters allow you greater control over the results returned by a MeiliSearch query.
WARNING
If using the GET route to perform a search, all parameters must be URL-encoded.
This is not necessary when using the POST
route or one of our SDKs.
Parameters
Query Parameter | Description | Default Value |
---|---|---|
q | Search terms | “” |
offset | Number of documents to skip | 0 |
limit | Maximum number of documents returned | 20 |
filter | Filter queries by an attribute’s value | null |
facetsDistribution | Display the count of matches per facet | null |
attributesToRetrieve | Attributes to display in the returned documents | [“*”] |
attributesToCrop | Attributes whose values have to be cropped | null |
cropLength | Maximum field value length | 200 |
attributesToHighlight | Highlight matching terms contained in an attribute | null |
matches | Return matching terms location | false |
sort | Sort search results by an attribute’s value | null |
Query (q)
Parameter: q
Expected value: any string
Default value: null
Sets the search terms.
WARNING
MeiliSearch only considers the first ten words of any given search query. This is necessary in order to deliver a fast search-as-you-type experience.
Additionally, keep in mind queries go through a normalization process that strips accents and diacritics, as well as making all terms lowercase.
Placeholder search
When q
isn’t specified, MeiliSearch performs a placeholder search. A placeholder search returns all searchable documents in an index, modified by any search parameters used and sorted by that index’s custom ranking rules. Since there is no query term, the built-in ranking rules (opens new window) do not apply.
If the index has no sort or custom ranking rules, the results are returned in the order of their internal database position.
TIP
Placeholder search is particularly useful when building a faceted search UI, as it allows users to view the catalog and alter sorting rules without entering a query.
Example
You can search for films mentioning shifu
by setting the q
parameter:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "shifu" }'
client.index('movies').search('shifu')
client.index('movies').search('shifu')
$client->index('movies')->search('shifu');
client.index("movies").search("shifu");
client.index('movies').search('shifu')
resp, err := client.Index("movies").Search("shifu", &meilisearch.SearchRequest{})
let results: SearchResults<Movie> = movies.search()
.with_query("shifu")
.execute()
.await
.unwrap();
client.index("movies").search(searchParameters(query: "shifu")) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('movies').search('shifu');
This will give you a list of documents that contain your query terms in at least one attribute.
{
"hits": [
{
"id": "50393",
"title": "Kung Fu Panda Holiday",
"poster": "https://image.tmdb.org/t/p/w500/rV77WxY35LuYLOuQvBeD1nyWMuI.jpg",
"overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers.",
"release_date": 1290729600,
"genres": [
"Animation",
"Family",
"TV Movie"
]
}
],
"query": "shifu"
}
Phrase search
If you enclose search terms in double quotes ("
), MeiliSearch will only return documents containing those terms in the order they were given. This is called a phrase search.
Phrase searches are case-insensitive and ignore soft separators such as -, ,, and :. Using a hard separator within a phrase search effectively splits it into multiple separate phrase searches: "Octavia.Butler"
will return the same results as "Octavia" "Butler"
.
You can combine phrase search and normal queries in a single search request. In this case, MeiliSearch will first fetch all documents with exact matches to the given phrase(s), and then proceed with its default behavior.
Example
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "\"african american\" horror" }'
client.index('movies')
.search('"african american" horror')
client.index('movies').search('"african american" horror')
$client->index('movies')->search('"african american" horror');
client.index("movies").search("\"african american\" horror");
client.index('movies').search('"african american" horror')
resp, err := client.Index("movies").Search("\"african american\" horror", &meilisearch.SearchRequest{})
let results: SearchResults<Movie> = movies
.search()
.with_query("\"african american\" horror")
.execute()
.await
.unwrap();
let searchParameters = SearchParameters(
query: "\"african american\" horror")
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('movies').search('"african american" horror');
Offset
Parameter: offset
Expected value: any positive integer
Default value: 0
Sets the starting point in the search results, effectively skipping over a given number of documents.
TIP
This parameter can be used together with limit
in order to paginate results.
Example
If you want to skip the first result in a query, set offset
to 1
:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "shifu", "offset": 1 }'
client.index('movies').search('shifu', {
offset: 1
})
client.index('movies').search('shifu', {
'offset': 1
})
$client->index('movies')->search('shifu', ['offset' => 1]);
SearchRequest searchRequest = new SearchRequest("shifu").setOffset(1);
client.index("movies").search(searchRequest);
client.index('movies').search('shifu', {
offset: 1
})
resp, err := client.Index("movies").Search("shifu", &meilisearch.SearchRequest{
Offset: 1,
})
let results: SearchResults<Movie> = movies.search()
.with_query("shifu")
.with_offset(1)
.execute()
.await
.unwrap();
let searchParameters = SearchParameters(
query: "shifu",
offset: 1)
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('movies').search('shifu', offset: 1);
Limit
Parameter: limit
Expected value: any positive integer
Default value: 20
Sets the maximum number of documents returned by a single query.
TIP
This parameter is often used together with offset
in order to paginate results.
Example
If you want your query to return only two documents, set limit
to 2
:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
- X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "shifu", "limit": 2 }'
client.index('movies').search('shifu', {
limit: 2
})
client.index('movies').search('shifu', {
'limit': 2
})
$client->index('movies')->search('shifu', ['limit' => 2]);
SearchRequest searchRequest = new SearchRequest("shifu").setLimit(2);
client.index("movies").search(searchRequest);
client.index('movies').search('shifu', {
limit: 2
})
resp, err := client.Index("movies").Search("shifu", &meilisearch.SearchRequest{
Limit: 2,
})
let results: SearchResults<Movie> = movies.search()
.with_query("shifu")
.with_limit(2)
.execute()
.await
.unwrap();
let searchParameters = SearchParameters(
query: "shifu",
limit: 2)
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('movies').search('shifu', limit: 2);
Filter
Parameter: filter
Expected value: a filter expression written as a string or an array of strings
Default value: []
Uses filter expressions to refine search results. Attributes used as filter criteria must be added to the filterableAttributes list.
Read our guide on filtering, faceted search and filter expressions.
Example
You can write a filter expression in string syntax using logical connectives:
"(genres = horror OR genres = mystery) AND director = 'Jordan Peele'"
You can write the same filter as an array:
[["genres = horror", "genres = mystery"], "director = 'Jordan Peele']
You can then use the filter in a search query:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "thriller", "filter": [["genres = Horror", "genres = Mystery"], "director = \"Jordan Peele\""] }'
client.index('movies')
.search('thriller', {
filter: [['genres = Horror', 'genres = Mystery'], 'director = "Jordan Peele"']
})
client.index('movies').search('thriller', {
'filter': [['genres = Horror', 'genres = Mystery'], 'director = "Jordan Peele"']
})
$client->index('movies')->search('thriller', ['filter' => [['genres = Horror', 'genres = Mystery'], 'director = "Jordan Peele"']]);
SearchRequest searchRequest =
new SearchRequest("thriller").setFilterArray(new String[][] {
new String[] {"genres = Horror", "genres = Mystery"},
new String[] {"director = \"Jordan Peele\""}});
client.index("movies").search(searchRequest);
client.index('movies').search('thriller', {
filter: [['genres = Horror', 'genres = Mystery'], 'director = "Jordan Peele"']
})
resp, err := client.Index("movies").Search("thriller", &meilisearch.SearchRequest{
Filter: [][]string{
[]string{"genres = Horror", "genres = Mystery"},
[]string{"director = \"Jordan Peele\""},
},
})
let results: SearchResults<Movie> = movies.search()
.with_query("thriller")
.with_filter("(genres = Horror AND genres = Mystery) OR director = \"Jordan Peele\"")
.execute()
.await
.unwrap();
let searchParameters = SearchParameters(
query: "thriller",
filter: [["genres = Horror", "genres = Mystery"], ["director = \"Jordan Peele\""]])
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('movies').search('thriller', filter: [
['genres = Horror', 'genres = Mystery'],
'director = "Jordan Peele"'
]);
Filtering results _geoRadius
If your documents contain _geo
data, you can use the _geoRadius
built-in filter rule to filter results according to their geographic position.
_geoRadius
establishes a circular area based on a central point and a radius. Results beyond this area will be excluded from your search. This filter rule requires three parameters: lat
, lng
and distance_in_meters
.
_geoRadius(lat, lng, distance_in_meters)
lat
and lng
should be geographic coordinates expressed as floating point numbers. distance_in_meters
indicates the radius of the area within which you want your results and should be an integer.
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl -X POST 'http://localhost:7700/indexes/restaurants/search' \
-H 'Content-type:application/json' \
--data-binary '{ "filter": "_geoRadius(45.4628328, 9.1076931, 2000)" }'
client.index('restaurants').search('', {
filter: ['_geoRadius(45.4628328, 9.1076931, 2000)'],
})
client.index('restaurants').search('', {
'filter': '_geoRadius(45.4628328, 9.1076931, 2000)'
})
$client->index('restaurants')->search('', ['filter' => '_geoRadius(45.4628328, 9.1076931, 2000)']);
SearchRequest searchRequest =
new SearchRequest("").setFilter(new String[] {"_geoRadius(45.4628328, 9.1076931, 2000)"});
client.index("restaurants").search(searchRequest);
client.index('restaurants').search('', { filter: '_geoRadius(45.4628328, 9.1076931, 2000)' })
resp, err := client.Index("restaurants").Search("", &meilisearch.SearchRequest{
Filter: "_geoRadius(45.4628328, 9.1076931, 2000)",
})
let results: SearchResults<Restaurant> = restaurants.search()
.with_filter("_geoRadius(45.4628328, 9.1076931, 2000)")
.execute()
.await
.unwrap();
let searchParameters = SearchParameters(
filter: ["_geoRadius(45.4628328, 9.1076931, 2000)"]
)
client.index("restaurants").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await await client
.index('restaurants')
.search('', filter: '_geoRadius(45.4628328, 9.1076931, 2000)');
Facets distribution
Parameter: facetsDistribution
Expected value: an array of attribute
s or ["*"]
Default value: null
Returns the number of documents matching the current search query for each given facet.
This parameter can take two values:
- An array of attributes:
facetsDistribution=["attributeA", "attributeB", …]
- An asterisk—this will return a count for all facets present in
filterableAttributes
NOTE
If an attribute used on facetsDistribution
has not been added to the filterableAttributes
list, it will be ignored.
Returned fields
When facetsDistribution
is set, the search results object contains two additional fields:
facetsDistribution
: The number of remaining candidates for each specified facetexhaustiveFacetsCount
: Atrue
orfalse
value indicating whether the count is exact (true
) or approximate (false
)
exhaustiveFacetsCount
is false
when the search matches contain too many different values for the given facetName
s. In this case, MeiliSearch stops the distribution count to prevent slowing down the request.
WARNING
exhaustiveFacetsCount
is not currently implemented and will always return false
.
Learn more about facet distribution in the filtering and faceted search guide.
Example
Given a movie database, suppose that you want to know the number of Batman
movies per genre:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "Batman", "facetsDistribution": ["genres"] }'
client.index('movies')
.search('Batman', {
facetsDistribution: ['genres']
})
client.index('movies').search('Batman', {
'facetsDistribution': ['genres']
})
$client->index('movies')->search('Batman', ['facetsDistribution' => ['genres']]);
SearchRequest searchRequest =
new SearchRequest("Batman").setFacetsDistribution(new String[] {"genres"});
client.index("movies").search(searchRequest);
client.index('movies').search('Batman', {
facets_distribution: ['genres']
})
resp, err := client.Index("movies").Search("Batman", &meilisearch.SearchRequest{
FacetsDistribution: []string{
"genres",
},
})
let results: SearchResults<Movie> = movies.search()
.with_query("Batman")
.with_facets_distribution(Selectors::Some(&["genres"]))
.execute()
.await
.unwrap();
let genres: &HashMap<String, usize> = results.facets_distribution.unwrap().get("genres").unwrap();
let searchParameters = SearchParameters(
query: "Batman",
facetsDistribution: ["genres"]])
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('movies').search('Batman', facetsDistribution: ['genres']);
You would get the following response:
{
…
"nbHits": 1684,
"query": "Batman",
"exhaustiveFacetsCount": false,
"facetsDistribution": {
"genres": {
"action": 273,
"animation": 118,
"adventure": 132,
"fantasy": 67,
"comedy": 475,
"mystery": 70,
"thriller": 217
}
}
}
Attributes to retrieve
Parameter: attributesToRetrieve
Expected value: an array of attribute
s or ["*"]
Default value: ["*"]
Configures which attributes will be retrieved in the returned documents.
If no value is specified, attributesToRetrieve
uses the displayedAttributes list, which by default contains all attributes found in the documents.
Example
To get only the overview
and title
fields, set attributesToRetrieve
to ["overview", "title"]
.
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "shifu", "attributesToRetrieve": ["overview", "title"] }'
client.index('movies').search('shifu', {
attributesToRetrieve: ['overview', 'title']
})
client.index('movies').search('shifu', {
'attributesToRetrieve': ['overview', 'title']
})
$client->index('movies')->search('shifu', ['attributesToRetrieve' => ['overview', 'title']]);
SearchRequest searchRequest =
new SearchRequest("a").setAttributesToRetrieve(new String[] {"overview", "title"});
client.index("movies").search(searchRequest);
client.index('movies').search('shifu', {
attributes_to_retrieve: ['overview', 'title']
})
resp, err := client.Index("movies").Search("shifu", &meilisearch.SearchRequest{
AttributesToRetrieve: []string{"overview", "title"},
})
let results: SearchResults<Movie> = movies.search()
.with_query("shifu")
.with_attributes_to_retrieve(Selectors::Some(&["overview", "title"]))
.execute()
.await
.unwrap();
let searchParameters = SearchParameters(
query: "shifu",
attributesToRetrieve: ["overview", "title"])
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client
.index('movies')
.search('shifu', attributesToRetrieve: ['overview', 'title']);
Attributes to crop
Parameter: attributesToCrop
Expected value: an array of attribute or ["*"]
Default value: null
Crops the selected attributes’ values in the returned results to the length indicated by the cropLength parameter.
When this parameter is set, a field called _formatted
will be added to hits
. The cropped version of each document will be available there.
Optionally, you can indicate a custom crop length for any of the listed attributes: attributesToCrop=["attributeNameA:25", "attributeNameB:150"]
. The custom crop length set in this way has priority over the cropLength
parameter.
Instead of supplying individual attributes
, you can provide ["*"]
as a value: attributesToCrop=["*"]
. This will crop the values of all attributes present in attributesToRetrieve.
Cropping starts at the first occurrence of the search query. It only keeps cropLength
characters on each side of the first match, rounded to match word boundaries.
If no query word is present in the cropped field, the crop will start from the first word.
Example
If you use shifu
as a search query and set the value of the cropLength
parameter to 10
:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "shifu", "attributesToCrop": ["overview"], "cropLength": 10 }'
client.index('movies').search('shifu', {
attributesToCrop: ['overview'],
cropLength: 10
})
client.index('movies').search('shifu', {
'attributesToCrop': ['overview'],
'cropLength': 10
})
$client->index('movies')->search('shifu', ['attributesToCrop' => ['overview'], 'cropLength' => 10]);
SearchRequest searchRequest =
new SearchRequest("shifu")
.setAttributesToCrop(new String[] {"overview"})
.setCropLength(10);
client.index("movies").search(searchRequest);
client.index('movies').search('shifu', {
attributes_to_crop: ['overview'],
cropLength: 10
})
resp, err := client.Index("movies").Search("shifu" &meilisearch.SearchRequest{
AttributesToCrop: []string{"overview"},
CropLength: 10,
})
let results: SearchResults<Movie> = movies.search()
.with_query("shifu")
.with_attributes_to_crop(Selectors::Some(&[("overview", None)]))
.with_crop_length(10)
.execute()
.await
.unwrap();
// Get the formatted results
let formatted_results: Vec<&Movie> = results.hits.iter().map(|r| r.formatted_result.as_ref().unwrap()).collect();
let searchParameters = SearchParameters(
query: "shifu",
attributesToCrop: "overview",
cropLength: 10)
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client
.index('movies')
.search('shifu', attributesToCrop: ['overview'], cropLength: 10);
You will get the following response with the cropped text in the _formatted
object:
{
"id": "50393",
"title": "Kung Fu Panda Holiday",
"poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
"overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
"release_date": 1290729600,
"_formatted": {
"id": "50393",
"title": "Kung Fu Panda Holiday",
"poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
"overview": "this year Shifu informs",
"release_date": 1290729600
}
}
Crop length
Parameter: cropLength
Expected value: a positive integer
Default value: 200
Configures the number of characters to keep on each side of the matching query term when using the attributesToCrop parameter. Note that this means there can be up to 2 * cropLength
characters in the cropped field.
If attributesToCrop
is not configured, cropLength
has no effect on the returned results.
Attributes to highlight
Parameter: attributesToHighlight
Expected value: an array of attributes or ["*"]
Default value: null
Highlights matching query terms in the given attributes. When this parameter is set, the _formatted
object is added to the response for each document, within which you can find the highlighted text.
Values can be supplied as an array of attributes: attributesToHighlight=["attributeA", "attributeB"]
.
Alternatively, you can provide ["*"]
as a value: attributesToHighlight=["*"]
. In this case, all the attributes present in attributesToRetrieve
will be assigned to attributesToHighlight
.
TIP
The highlighting performed by this parameter consists of wrapping matching query terms in <em>
tags. Neither this tag nor this behavior can be modified.
If a different type of highlighting is desired, we recommend the matches parameter, which provides much finer control over the output.
Example
If you wanted to highlight query matches that appear within the overview
attribute:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "winter feast", "attributesToHighlight": ["overview"] }'
client.index('movies').search('winter feast', {
attributesToHighlight: ['overview']
})
client.index('movies').search('winter feast', {
'attributesToHighlight': ['overview']
})
$client->index('movies')->search('winter feast', ['attributesToHighlight' => ['overview']]);
SearchRequest searchRequest =
new SearchRequest("and").setAttributesToHighlight(new String[] {"overview"});
client.index("movies").search(searchRequest);
client.index('movies').search('winter feast', {
attributes_to_highlight: ['overview']
})
resp, err := client.Index("movies").Search("winter feast", &meilisearch.SearchRequest{
AttributesToHighlight: []string{"overview"},
})
let results: SearchResults<Movie> = movies.search()
.with_query("winter feast")
.with_attributes_to_highlight(Selectors::Some(&["overview"]))
.execute()
.await
.unwrap();
// Get the formatted results
let formatted_results: Vec<&Movie> = results.hits.iter().map(|r| r.formatted_result.as_ref().unwrap()).collect();
let searchParameters = SearchParameters(
query: "winter feast",
attributesToHighlight: ["overview"])
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client
.index('movies')
.search('winter feast', attributesToHighlight: ['overview']);
You would get the following response with the highlighted version in the _formatted
object:
{
"id": "50393",
"title": "Kung Fu Panda Holiday",
"poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
"overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
"release_date": 1290729600,
"_formatted": {
"id": "50393",
"title": "Kung Fu Panda Holiday",
"poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
"overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year <em>Shifu</em> informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between <em>Shifu</em> and Mr. Ping.",
"release_date": 1290729600
}
}
Matches
Parameter: matches
Expected value: true
or false
Default value: false
Adds an object to the search response (_matchesInfo
) containing the location of each occurrence of queried terms across all fields. This is useful when you need more control than offered by our built-in highlighting.
The beginning of a matching term within a field is indicated by start
, and its length by length
.
WARNING
start
and length
are measured in bytes and not the number of characters. For example, ü
represents two bytes but one character.
matches
does not work with array or object values—only strings.
Example
If you set matches
to true
and search for shifu
:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "winter feast", "matches": true }'
client.index('movies').search('winter feast', {
matches: true
})
client.index('movies').search('winter feast', {
'matches': 'true'
})
$client->index('movies')->search('winter feast', ['attributesToHighlight' => ['overview'], 'matches' => true]);
SearchRequest searchRequest = new SearchRequest("winter feast").setMatches(true);
SearchResult searchResult = index.search(searchRequest);
client.index('movies').search('winter feast', {
matches: true
})
resp, err := client.Index("movies").Search("winter feast", &meilisearch.SearchRequest{
Matches: true,
})
let results: SearchResults<Movie> = movies.search()
.with_query("winter feast")
.with_matches(true)
.execute()
.await
.unwrap();
// Get the matches info
let matched_info: Vec<&HashMap<String, Vec<MatchRange>>> = results.hits.iter().map(|r| r.matches_info.as_ref().unwrap()).collect();
let searchParameters = SearchParameters(
query: "winter feast",
matches: true)
client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('movies').search('winter feast', matches: true);
You would get the following response with information about the matches in the _matchesInfo
object:
{
"id": "50393",
"title": "Kung Fu Panda Holiday",
"poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
"overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
"release_date": 1290729600,
"_matchesInfo": {
"overview": [
{
"start": 159,
"length": 5
},
{
"start": 361,
"length": 5
}
]
}
}
Sort
Parameter: sort
Expected value: a list of attributes written as an array or as a comma-separated string
Default value: null
Sorts search results at query time according to the specified attributes and indicated order.
Each attribute in the list must be followed by a colon (:
) and the preferred sorting order: either ascending (asc
) or descending (desc
).
NOTE
Attribute order is meaningful. The first attributes in a list will be given precedence over those that come later.
For example, sort="price:asc,author:desc
will prioritize price
over author
when sorting results.
When using the POST
route, sort
expects an array of strings.
When using the GET
route, sort
expects the list as a comma-separated string.
Read more about sorting search results in our dedicated guide.
Example
You can search for science fiction books ordered from cheapest to most expensive:
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl \
-X POST 'http://localhost:7700/indexes/books/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "science fiction",
"sort": [
"price:asc"
]
}'
client.index('books').search('science fiction', {
sort: ['price:asc'],
})
client.index('books').search('science fiction', {
'sort': ['price:asc']
})
$client->index('books')->search('science fiction', ['sort' => ['price:asc']]);
SearchRequest searchRequest = new SearchRequest("science fiction").setSort(new String[] {"price:asc"});
client.index("search_parameter_guide_sort_1").search(searchRequest);
client.index('books').search('science fiction', { sort: ['price:asc'] })
resp, err := client.Index("books").Search("science fiction", &meilisearch.SearchRequest{
Sort: []string{
"price:asc",
},
})
let results: SearchResults<Books> = books.search()
.with_query("science fiction")
.with_sort(&["price:asc"])
.execute()
.await
.unwrap();
let searchParameters = SearchParameters(
query: "science fiction",
sort: ["price:asc"]
)
client.index("books").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('books').search('science fiction', sort: ['price:asc']);
Sorting results with _geoPoint
When dealing with documents containing geolocation data, you can use _geoPoint
to sort results based on their distance from a specific geographic location.
_geoPoint
is a sorting function that requires two floating point numbers indicating a location’s latitude and longitude. You must also specify whether the sort should be ascending (asc
) or descending (desc
):
<>
cURL
JS
Python
PHP
Java
Ruby
Go
Rust
Swift
Dart
curl -X POST 'http://localhost:7700/indexes/restaurants/search' \
-H 'Content-type:application/json' \
--data-binary '{ "sort": ["_geoPoint(48.8583701,2.2922926):asc"] }'
client.index('restaurants').search('', {
sort: ['_geoPoint(48.8583701,2.2922926):asc'],
})
client.index('restaurants').search('', {
'sort': ['_geoPoint(48.8583701,2.2922926):asc']
})
$client->index('restaurants')->search('', ['sort' => ['_geoPoint(48.8583701,2.2922926):asc']]);
SearchRequest searchRequest =
new SearchRequest("").setSort(new String[] {"_geoPoint(48.8583701,2.2922926):asc"});
client.index("restaurants").search(searchRequest);
client.index('restaurants').search('', { sort: ['_geoPoint(48.8583701,2.2922926):asc'] })
resp, err := client.Index("restaurants").Search("", &meilisearch.SearchRequest{
Sort: []string{
"_geoPoint(48.8583701,2.2922926):asc",
},
})
let results: SearchResults<Restaurant> = restaurants.search()
.with_sort(&["_geoPoint(48.8583701,2.2922926):asc"])
.execute()
.await
.unwrap();
let searchParameters = SearchParameters(
sort: ["_geoPoint(48.8583701,2.2922926):asc"]
)
client.index("restaurants").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
switch result {
case .success(let searchResult):
print(searchResult)
case .failure(let error):
print(error)
}
}
await client.index('restaurants').search('', sort: ['_geoPoint(48.8583701,2.2922926):asc']);
Queries using _geoPoint
will always include a geoDistance
field containing the distance in meters between the document location and the _geoPoint
:
[
{
"id": 1,
"name": "Nàpiz' Milano",
"_geo": {
"lat": 45.4777599,
"lng": 9.1967508
},
"_geoDistance": 1532
}
]
You can read more about location-based sorting in our dedicated guide.