Skip to content

meilisearch/meilisearch-java

Repository files navigation

Meilisearch Java

Meilisearch Java

Version Tests License Bors enabled Code Coverage

⚑ The Meilisearch API client written for Java β˜•οΈ

Meilisearch Java is the Meilisearch API client for Java developers.

Meilisearch is an open-source search engine. Learn more about Meilisearch.

Table of Contents

πŸ“– Documentation

This readme contains all the documentation you need to start using this Meilisearch SDK.

For general information on how to use Meilisearchβ€”such as our API reference, tutorials, guides, and in-depth articlesβ€”refer to our main documentation website.

⚑ Supercharge your Meilisearch experience

Say goodbye to server deployment and manual updates with Meilisearch Cloud. Get started with a 14-day free trial! No credit card required.

πŸ”§ Installation

meilisearch-java is available from JCentral official repository. To be able to import this package, declare it as a dependency in your project:

Maven

Add the following code to the <dependencies> section of your project:

<dependency>
  <groupId>com.meilisearch.sdk</groupId>
  <artifactId>meilisearch-java</artifactId>
  <version>0.11.9</version>
  <type>pom</type>
</dependency>

Gradle

Add the following line to the dependencies section of your build.gradle:

implementation 'com.meilisearch.sdk:meilisearch-java:0.11.9'

⚠️ meilisearch-java also requires okhttp as a peer dependency.

Run Meilisearch

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.

πŸš€ Getting started

Add documents

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("genres",new JSONArray("[\"Romance\",\"Drama\"]")));
      add(new JSONObject().put("id", "2").put("title", "Wonder Woman").put("genres",new JSONArray("[\"Action\",\"Adventure\"]")));
      add(new JSONObject().put("id", "3").put("title", "Life of Pi").put("genres",new JSONArray("[\"Adventure\",\"Drama\"]")));
      add(new JSONObject().put("id", "4").put("title", "Mad Max: Fury Road").put("genres",new JSONArray("[\"Adventure\",\"Science Fiction\"]")));
      add(new JSONObject().put("id", "5").put("title", "Moana").put("genres",new JSONArray("[\"Fantasy\",\"Action\"]")));
      add(new JSONObject().put("id", "6").put("title", "Philadelphia").put("genres",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); // => { "taskUid": 0 }
  }
}

With the taskUid, you can check the status (enqueued, canceled, processing, succeeded or failed) of your documents addition using the task endpoint.

Basic Search

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, genres:[Romance, Drama]}], offset=0, limit=20, estimatedTotalHits=1, facetDistribution=null, processingTimeMs=3, query=carlo)

Custom Search

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")
  .setShowMatchesPosition(true)
  .setAttributesToHighlight(new String[]{"title"})
);
System.out.println(results.getHits());
  • Output:
[{
  "id":3,
  "title":"Life of Pi",
  "genres":["Adventure","Drama"],
  "_formatted":{
    "id":3,
    "title":"Life <em>of</em> Pi",
    "genres":["Adventure","Drama"]
  },
  "_matchesPosition":{
    "title":[{
      "start":5.0,
      "length":2.0
    }]
  }
}]

Custom Search With Filters

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,
  "estimatedTotalHits": 1,
  "processingTimeMs": 0,
  "query": "wonder"
}

πŸ›  Customization

JSON

Default JSON GsonJsonHandler

The default JSON library is Gson. You can however use another library with the JsonHandler Class.

Notes: We strongly recommend using the Gson library.

Using JacksonJsonHandler

Initialize your Config and assign it a new JacksonJsonHandler object as JsonHandler. Set up your Client with it.

import com.meilisearch.sdk.json.JacksonJsonHandler;

Config config = new Config("http://localhost:7700", "masterKey", new JacksonJsonHandler());
Client client = new Client(config);

Use a Custom JsonHandler

To create your own JSON handler, you must conform to the JsonHandler interface by implementing its two methods.

    String encode(Object o) throws Exception;

    <T> T decode(Object o, Class<?> targetClass, Class<?>... parameters) throws Exception;

Then create your client by initializing your Config with your new handler.

Config config = new Config("http://localhost:7700", "masterKey", new myJsonHandler());
Client client = new Client(config);

πŸ€– Compatibility with Meilisearch

This package guarantees compatibility with version v1.x of Meilisearch, but some features may not be present. Please check the issues for more info.

πŸ’‘ Learn more

The following sections in our main documentation website may interest you:

βš™οΈ Contributing

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.