Meilisearch | Documentation | Slack | Roadmap | Website | FAQ
β‘ The Meilisearch API client written for Java βοΈ
Meilisearch Java is the Meilisearch API client for Java developers.
Meilisearch is an open-source search engine. Discover what Meilisearch is!
- π Documentation
- π§ Installation
- π Getting Started
- π Customization
- π€ Compatibility with Meilisearch
- π‘ Learn More
- βοΈ Development Workflow and Contributing
See our Documentation or our API References.
meilisearch-java
is available from JCentral official repository. To be able to import this package, declare it as a dependency in your project:
Add the following code to the <dependencies>
section of your project:
<dependency>
<groupId>com.meilisearch.sdk</groupId>
<artifactId>meilisearch-java</artifactId>
<version>0.7.0</version>
<type>pom</type>
</dependency>
Add the following line to the dependencies
section of your build.gradle
:
implementation 'com.meilisearch.sdk:meilisearch-java:0.7.0'
There are many easy ways to download and run a Meilisearch instance.
For example, using the curl
command in your Terminal:
# Install Meilisearch
curl -L https://install.meilisearch.com | sh
# Launch Meilisearch
./meilisearch --master-key=masterKey
NB: you can also download Meilisearch from Homebrew or APT or even run it using Docker.
package com.meilisearch.sdk;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
class TestMeilisearch {
public static void main(String[] args) throws Exception {
JSONArray array = new JSONArray();
ArrayList items = new ArrayList() {{
add(new JSONObject().put("id", "1").put("title", "Carol").put("genre",new JSONArray("[\"Romance\",\"Drama\"]")));
add(new JSONObject().put("id", "2").put("title", "Wonder Woman").put("genre",new JSONArray("[\"Action\",\"Adventure\"]")));
add(new JSONObject().put("id", "3").put("title", "Life of Pi").put("genre",new JSONArray("[\"Adventure\",\"Drama\"]")));
add(new JSONObject().put("id", "4").put("title", "Mad Max: Fury Road").put("genre",new JSONArray("[\"Adventure\",\"Science Fiction\"]")));
add(new JSONObject().put("id", "5").put("title", "Moana").put("genre",new JSONArray("[\"Fantasy\",\"Action\"]")));
add(new JSONObject().put("id", "6").put("title", "Philadelphia").put("genre",new JSONArray("[\"Drama\"]")));
}};
array.put(items);
String documents = array.getJSONArray(0).toString();
Client client = new Client(new Config("http://localhost:7700", "masterKey"));
// An index is where the documents are stored.
Index index = client.index("movies");
// If the index 'movies' does not exist, Meilisearch creates it when you first add the documents.
index.addDocuments(documents); // => { "uid": 0 }
}
}
With the taskUid
, you can check the status (enqueued
, processing
, succeeded
or failed
) of your documents addition using the task endpoint.
A basic search can be performed by calling index.search()
method, with a simple string query.
import com.meilisearch.sdk.model.SearchResult;
// Meilisearch is typo-tolerant:
SearchResult results = index.search("carlo");
System.out.println(results);
- Output:
SearchResult(hits=[{id=1.0, title=Carol, genre:[Romance, Drama]}], offset=0, limit=20, nbHits=1, exhaustiveNbHits=false, facetsDistribution=null, exhaustiveFacetsCount=false, processingTimeMs=3, query=carlo)
If you want a custom search, the easiest way is to create a SearchRequest
object, and set the parameters that you need.
All the supported options are described in the search parameters section of the documentation.
import com.meilisearch.sdk.SearchRequest;
// ...
SearchResult results = index.search(
new SearchRequest("of")
.setMatches(true)
.setAttributesToHighlight(new String[]{"title"})
);
System.out.println(results.getHits());
- Output:
[{
"id":3,
"title":"Life of Pi",
"genre":["Adventure","Drama"],
"_formatted":{
"id":3,
"title":"Life <em>of</em> Pi",
"genre":["Adventure","Drama"]
},
"_matchesInfo":{
"title":[{
"start":5,
"length":2
}]
}
}]
If you want to enable filtering, you must add your attributes to the filterableAttributes
index setting.
index.updateFilterableAttributesSettings(new String[]
{
"id",
"genres"
});
You only need to perform this operation once.
Note that Meilisearch will rebuild your index whenever you update filterableAttributes
. Depending on the size of your dataset, this might take time. You can track the process using the task status.
Then, you can perform the search:
index.search(
new SearchRequest("wonder")
.setFilter(new String[] {"id > 1 AND genres = Action"})
);
{
"hits": [
{
"id": 2,
"title": "Wonder Woman",
"genres": ["Action","Adventure"]
}
],
"offset": 0,
"limit": 20,
"nbHits": 1,
"processingTimeMs": 0,
"query": "wonder"
}
The default JSON can be created by calling the default constructor of JsonbJsonHandler
class which will create a config of type JsonbConfig
and using this config. It will initialize the mapper variable by calling the create method of JsonbBuilder
class.
To create a custom JSON handler, create an object of GsonJsonHandler and send the GSON object in the parameterized constructor.
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.serializeNulls()
.create();
private GsonJsonHandler jsonGson = new GsonJsonHandler(gson);
jsonGson.encode("your_data");
Another method is to create an object of JacksonJsonHandler
and set the required parameters. The supported option is an object of ObjectMapper
. It's passed as a parameter to the JacksonJsonHandler
βs parameterized constructor. This is used to initialize the mapper variable.
The mapper variable is responsible for the encoding and decoding of the JSON.
Using the custom JSON:
Config config = new Config("http://localhost:7700", "masterKey");
HttpAsyncClient client = HttpAsyncClients.createDefault();
ApacheHttpClient client = new ApacheHttpClient(config, client);
private final JsonHandler jsonHandler = new JacksonJsonHandler(new ObjectMapper());
private final RequestFactory requestFactory = new BasicRequestFactory(jsonHandler);
private final GenericServiceTemplate serviceTemplate = new GenericServiceTemplate(client, jsonHandler, requestFactory);
private final ServiceTemplate serviceTemplate;
serviceTemplate.getProcessor().encode("your_data");
Another method of creating a JSON handler is to create an object of JsonbJsonHandler
and send the Jsonb
object to the parameterized constructor.
Jsonb jsonb = JsonbBuilder.create();
private JsonbJsonHandler jsonbHandler = new JsonbJsonHandler(jsonb);
jsonbHandler.encode("your_data");
To create a custom Client
handler, create an object of Client
and set the required parameters.
A Config
object should be passed, containing your host URL and your API key.
Config config = new Config("http://localhost:7700", "masterKey");
return new Client(config);
The Client(config)
constructor sets the config instance to the member variable. It also sets the 3 other instances namely gson()
, IndexesHandler(config)
and DumpHandler(config)
.
Using the custom Client
:
Config config = new Config("http://localhost:7700", "masterKey");
HttpAsyncClient client = HttpAsyncClients.createDefault();
ApacheHttpClient customClient = new ApacheHttpClient(config, client);
customClient.index("movies").search("American ninja");
To create a custom HTTP request, create an object of BasicHttpRequest
and set the required parameters.
The supported options are as follows:
- HTTP method: a
String
that can be set as following values:HEAD
,GET
,POST
,PUT
, orDELETE
. - Path: a
String
corresponding to the endpoint of the API. - Headers: a
Map<String,String>
containing the header parameters in the form of key-value pair. - Content: the
String
of your content.
return new BasicHttpRequest(
method,
path,
headers,
content == null ? null : this.jsonHandler.encode(content));
Alternatively, there is an interface RequestFactory
which has a method create
.
In order to call this method, create an object of RequestFactory
and call the method by passing the required parameters.
Using the custom Http Request:
public interface RequestFactory {
<T> HttpRequest<?> create(
HttpMethod method, String path, Map<String, String> headers, T content);
}
private final RequestFactory requestFactory;
requestFactory.create(HttpMethod.GET, "/health", Collections.emptyMap(), {"id":"3"});
This package only guarantees compatibility with the version v0.25.0 of Meilisearch.
The following sections may interest you:
- Manipulate documents: see the API references or read more about documents.
- Search: see the API references or follow our guide on search parameters.
- Manage the indexes: see the API references or read more about indexes.
- Configure the index settings: see the API references or follow our guide on settings parameters.
Any new contribution is more than welcome in this project!
If you want to know more about the development workflow or want to contribute, please visit our contributing guidelines for detailed instructions!
Meilisearch provides and maintains many SDKs and Integration tools like this one. We want to provide everyone with an amazing search experience for any kind of project. If you want to contribute, make suggestions, or just know what's going on right now, visit us in the integration-guides repository.