Meilisearch Java SDK

repository·main·Indexed 42 days ago

https://github.com/meilisearch/meilisearch-java

The official API client for interacting with the Meilisearch search engine from Java applications. Compatible with Meilisearch v1.x and requiring JDK 17 or above, the SDK provides tools for managing indexes, performing typo-tolerant searches with filters and pagination, handling documents, and managing dynamic search rules, API keys, and webhooks. It uses Gson by default but supports custom JSON handlers like Jackson.

Tokens
7.8K
Snippets
25
Records
45
Agent score
53%

What's inside Meilisearch Java

  1. Install the Meilisearch Java SDK

    main

    Add meilisearch-java as a dependency in your project. Note that this SDK requires okhttp as a peer dependency.

    Maven

    Add the following to your <dependencies> section:

    Gradle

    Add the following to your dependencies block in build.gradle:

    <!-- Maven -->
    <dependency>
      <groupId>com.meilisearch.sdk</groupId>
      <artifactId>meilisearch-java</artifactId>
      <version>0.21.0</version>
      <type>pom</type>
    </dependency>
    
    <!-- Gradle -->
    implementation 'com.meilisearch.sdk:meilisearch-java:0.21.0'
  2. Customize the JSON handler

    main

    The SDK uses Gson by default. You can switch to Jackson or provide a custom implementation of the JsonHandler interface.

    Using Jackson

    Initialize your Config with a JacksonJsonHandler before creating the Client.

    Implementing a Custom JsonHandler

    Implement the following methods:

    • String encode(Object o) throws Exception
    • <T> T decode(Object o, Class<?> targetClass, Class<?>... parameters) throws Exception
    // Using Jackson
    import com.meilisearch.sdk.json.JacksonJsonHandler;
    
    Config config = new Config("http://localhost:7700", "masterKey", new JacksonJsonHandler());
    Client client = new Client(config);
    
    // Using Custom Handler
    Config config = new Config("http://localhost:7700", "masterKey", new myJsonHandler());
    Client client = new Client(config);
  3. Run Meilisearch and the Java client using Docker Compose

    main

    This docker-compose.yml file sets up a development environment containing two services: meilisearch (the search engine) and package (the Java client/application).

    Meilisearch Service

    • Image: getmeili/meilisearch-enterprise:latest
    • Ports: Exposes port 7700.
    • Environment Variables:
      • MEILI_MASTER_KEY: The master key used for authentication. Set to masterKey by default in this config.
      • MEILI_NO_ANALYTICS: Set to true to disable analytics.

    Package (Java Client) Service

    • Image: azul/zulu-openjdk:17-latest
    • Environment Variables:
      • MEILISEARCH_HOST: The URL of the Meilisearch instance. Set to http://meilisearch:7700 to allow the Java application to communicate with the meilisearch service within the Docker network.
    • Volumes: Mounts the current directory (./) to /home/package inside the container, allowing you to run your Java code from your local filesystem.
    services:
      package:
        image: azul/zulu-openjdk:17-latest
        tty: true
        stdin_open: true
        working_dir: /home/package
        environment:
          - MEILISEARCH_HOST=http://meilisearch:7700
        depends_on:
          - meilisearch
        links:
          - meilisearch
        volumes:
          - ./:/home/package
    
    meilisearch:
        image: getmeili/meilisearch-enterprise:latest
        ports:
          - "7700"
        environment:
          - MEILI_MASTER_KEY=masterKey
          - MEILI_NO_ANALYTICS=true
  4. Perform a custom search with parameters

    main

    For advanced search requirements, create a SearchRequest object and use its setter methods to configure parameters such as highlighting or match positions.

    import com.meilisearch.sdk.SearchRequest;
    
    // ...
    
    SearchResult results = (SearchResult) index.search(
        new SearchRequest("of")
            .setShowMatchesPosition(true)
            .setAttributesToHighlight(new String[]{"title"})
    );
    System.out.println(results.getHits());
  5. Perform a paginated search

    main

    To implement pagination, use SearchRequest with setPage() and setHitsPerPage(). The result will be an instance of SearchResultPaginated.

    import com.meilisearch.sdk.SearchResultPaginated;
    
    // ...
    
    SearchResultPaginated results = (SearchResultPaginated) index.search(
        new SearchRequest("wonder")
            .setPage(1)
            .setHitsPerPage(20)
    );
  6. Perform a basic search

    main

    A basic search can be performed by calling the index.search() method with a simple string query. The search is typo-tolerant by default.

    import com.meilisearch.sdk.model.SearchResult;
    
    // Meilisearch is typo-tolerant:
    SearchResult results = index.search("carlo");
    System.out.println(results);
  7. Perform a search with filters

    main

    To use filters in a search, you must first register the attributes you wish to filter by using updateFilterableAttributesSettings. This is a one-time operation that triggers an index rebuild. Once configured, you can pass a filter string to a SearchRequest.

    // 1. Configure filterable attributes (perform once)
    index.updateFilterableAttributesSettings(new String[] {
      "id",
      "genres"
    });
    
    // 2. Perform the search with a filter
    index.search(
      new SearchRequest("wonder")
          .setFilter(new String[] {"id > 1 AND genres = Action"})
    );
  8. Add documents to a Meilisearch index

    main

    To add documents, initialize a Client with a Config object containing your Meilisearch host and master key. Access an Index using the client, and call addDocuments() with a JSON string representing your documents.

    Note: If the index does not exist, Meilisearch will create it automatically upon the first document addition. The operation returns a taskUid which can be used to track the status (enqueued, canceled, processing, succeeded, or failed) via the Meilisearch task endpoint.

    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 }
  9. Add, update, and delete documents in an index

    main

    The Index class provides several methods for managing document lifecycle:

    Adding/Replacing Documents

    • addDocuments(String document): Adds documents provided in JSON or CSV format.
    • addDocumentsInBatches(String document, Integer batchSize, String primaryKey): Splits a large JSON array into smaller batches to avoid request size limits. Defaults to a batch size of 1000 if batchSize is not provided.
    • You can specify a primaryKey and a csvDelimiter if adding CSV data.

    Updating Documents

    • updateDocuments(String document): Updates existing documents. Unlike addDocuments, this performs a partial update.
    • updateDocumentsInBatches(...): Similar to adding, allows updating large sets of documents in chunks.

    Deleting Documents

    • deleteDocument(String identifier): Deletes a single document by its ID.
    • deleteDocumentsByFilter(String filter): Deletes all documents matching a specific filter expression.
    • deleteAllDocuments(): Removes all documents from the index.

    Note: deleteDocuments(List<String> identifiers) is deprecated; use filters or individual deletions where possible.

    // Add documents (JSON string)
    index.addDocuments("[{\"id\": 1, \"name\": \"foo\"}]");
    
    // Add documents in batches
    index.addDocumentsInBatches(largeJsonString, 500, "id");
    
    // Update documents
    index.updateDocuments("[{\"id\": 1, \"name\": \"bar\"}]");
    
    // Delete by filter
    index.deleteDocumentsByFilter("category = 'books'");