Giter Club home page Giter Club logo

meilisearch-java's Introduction

MeiliSearch Java

MeiliSearch Java

Version Tests License Bors enabled

⚡ 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!

Table of Contents

📖 Documentation

See our Documentation or our API References.

🔧 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.5.0</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.5.0'

🚀 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("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); // => { "updateId": 0 }
  }
}

With the updateId, you can check the status (enqueued, processing, processed or failed) of your documents addition using the update 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, genre:[Romance, Drama]}], offset=0, limit=20, nbHits=1, exhaustiveNbHits=false, facetsDistribution=null, exhaustiveFacetsCount=false, 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")
  .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
    }]
  }
}]

Custom Search With Filters

If you want to enable filtering, you must add your attributes to the filterableAttributes index setting.

await index.updateAttributesForFaceting([
    '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 update status.

Then, you can perform the search:

await index.search(
  'wonder',
  {
    filter: ['id > 1 AND genres = Action']
  }
)
{
  "hits": [
    {
      "id": 2,
      "title": "Wonder Woman",
      "genres": ["Action","Adventure"]
    }
  ],
  "offset": 0,
  "limit": 20,
  "nbHits": 1,
  "processingTimeMs": 0,
  "query": "wonder"
}

🛠 Customization

JSON

Basic JSON

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.

Creating a Custom GsonJsonHandler

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");

Creating a Custom JacksonJsonHandler

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");

Creating a Custom `JsonbJsonHandler

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");

Custom Client

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");

Custom Http Request

To create a custom HTTP request, create an object of BasicHttpRequest and set the required parameters.

The supported options are as follows:

  1. HTTP method: a String that can be set as following values: HEAD, GET, POST, PUT, or DELETE.
  2. Path: a String corresponding to the endpoint of the API.
  3. Headers: a Map<String,String> containing the header parameters in the form of key-value pair.
  4. 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"});

🤖 Compatibility with MeiliSearch

This package only guarantees the compatibility with the version v0.23.0 of MeiliSearch.

💡 Learn More

The following sections may interest you:

⚙️ Development Workflow and 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.

meilisearch-java's People

Contributors

alallema avatar amiralbl3ndic avatar ansavanix avatar arjunrc143 avatar bors[bot] avatar curquiza avatar dependabot-preview[bot] avatar dependabot[bot] avatar dichotommy avatar eskombro avatar ezienecker avatar fharper avatar inomag avatar ishika22 avatar johandelvallev avatar kination avatar luis-valdez avatar lumineca avatar mayralgr avatar meili-bot avatar mohitsaxenaknoldus avatar nicolasvienot avatar niemannd avatar ppshobi avatar ujjavala avatar vishnugt avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.