diff --git a/README.md b/README.md index de513bea..fd535389 100644 --- a/README.md +++ b/README.md @@ -71,28 +71,73 @@ implementation 'com.meilisearch.sdk:meilisearch-java:0.3.1' ```java import com.meilisearch.sdk.Client; +import com.meilisearch.sdk.ClientBuilder; import com.meilisearch.sdk.Config; -import com.meilisearch.sdk.Index; +import com.meilisearch.sdk.api.documents.DocumentHandler; +import com.meilisearch.sdk.api.documents.Update; +import com.meilisearch.sdk.api.index.Index; +import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; +import com.meilisearch.sdk.http.ApacheHttpClient; +import com.meilisearch.sdk.json.GsonJsonHandler; -class TestMeiliSearch { +import java.util.Collections; +import java.util.Map; + +public class TestMeiliSearch { public static void main(String[] args) throws Exception { final String documents = "[" - + "{\"book_id\": 123, \"title\": \"Pride and Prejudice\"}," - + "{\"book_id\": 456, \"title\": \"Le Petit Prince\"}," - + "{\"book_id\": 1, \"title\": \"Alice In Wonderland\"}," - + "{\"book_id\": 1344, \"title\": \"The Hobbit\"}," - + "{\"book_id\": 4, \"title\": \"Harry Potter and the Half-Blood Prince\"}," - + "{\"book_id\": 2, \"title\": \"The Hitchhiker\'s Guide to the Galaxy\"}" + + "{\"id\": 123, \"title\": \"Pride and Prejudice\"}," + + "{\"id\": 456, \"title\": \"Le Petit Prince\"}," + + "{\"id\": 1, \"title\": \"Alice In Wonderland\"}," + + "{\"id\": 1344, \"title\": \"The Hobbit\"}," + + "{\"id\": 4, \"title\": \"Harry Potter and the Half-Blood Prince\"}," + + "{\"id\": 2, \"title\": \"The Hitchhiker\'s Guide to the Galaxy\"}" + "]"; - Client client = new Client(new Config("http://localhost:7700", "masterKey")); + Map> modelMapping = Collections.singletonMap("books", Book.class); + Config config = new Config("http://localhost:7700", "masterKey", modelMapping); + // set httpClient and JsonHandler explicit + ApacheHttpClient httpClient = new ApacheHttpClient(config); + GsonJsonHandler handler = new GsonJsonHandler(); + Client client = ClientBuilder.withConfig(config).withHttpClient(httpClient).withJsonHandler(handler).build(); + // let the sdk autodetect jsonhandler and httpclient based on the classes in the classpath + client = ClientBuilder.withConfig(config).build(); + + try { + Index index = client.index().getOrCreateIndex("books", "id"); + DocumentHandler bookHandler = client.documents("books"); + Update update = bookHandler.addDocuments(documents); + bookHandler.waitForPendingUpdate(update.getUpdateId()); + + + } catch (MeiliSearchRuntimeException e) { + // an MeiliSearchRuntimeException will be thrown in case something went wrong + e.printStackTrace(); + } + } +} - // An index is where the documents are stored. - Index index = client.index("books"); +public class Book { + int id; + String title; + + public int getId() { + return id; + } + + public Book setId(int id) { + this.id = id; + return this; + } + + public String getTitle() { + return title; + } - // If the index 'books' does not exist, MeiliSearch creates it when you first add the documents. - index.addDocuments(documents); // => { "updateId": 0 } + public Book setTitle(String title) { + this.title = title; + return this; } } ``` @@ -101,20 +146,19 @@ With the `updateId`, you can check the status (`enqueued`, `processed` or `faile #### Basic Search -A basic search can be performed by calling `index.search()` method, with a simple string query. +A basic search can be performed by calling `search()` method on the handler, with a simple string query. ```java import com.meilisearch.sdk.model.SearchResult; -// MeiliSearch is typo-tolerant: -SearchResult results = index.search("harry pottre"); -System.out.println(results); +DocumentHandler bookHandler = client.documents("books"); +SearchResponse alice = bookHandler.search("Alice"); ``` - Output: ``` -SearchResult(hits=[{book_id=4.0, title=Harry Potter and the Half-Blood Prince}], offset=0, limit=20, nbHits=1, exhaustiveNbHits=false, facetsDistribution=null, exhaustiveFacetsCount=false, processingTimeMs=3, query=harry pottre) +SearchResponse(hits=[{id=4.0, title=Harry Potter and the Half-Blood Prince}], offset=0, limit=20, nbHits=1, exhaustiveNbHits=false, facetsDistribution=null, exhaustiveFacetsCount=false, processingTimeMs=3, query=harry pottre) ``` #### Custom Search @@ -127,10 +171,10 @@ import com.meilisearch.sdk.SearchRequest; // ... -String results = index.search( +SearchResult result = bookHandler.search( new SearchRequest("in") .setMatches(true) - .setAttributesToHighlight(new String[]{"title"}) + .setAttributesToHighlight(Arrays.asList("title")) ); System.out.println(results.getHits()); ``` @@ -139,10 +183,10 @@ System.out.println(results.getHits()); ```json [{ - "book_id":1, + "id":1, "title":"Alice In Wonderland", "_formatted":{ - "book_id":1, + "id":1, "title":"Alice In Wonderland" }, "_matchesInfo":{ diff --git a/build.gradle b/build.gradle index a3e5018a..d4cdf90e 100644 --- a/build.gradle +++ b/build.gradle @@ -25,7 +25,6 @@ java { repositories { mavenCentral() // Required for Lombok dependency - jcenter() } configurations { diff --git a/src/main/java/com/meilisearch/sdk/Client.java b/src/main/java/com/meilisearch/sdk/Client.java index 16331fb3..cd4c5c5e 100644 --- a/src/main/java/com/meilisearch/sdk/Client.java +++ b/src/main/java/com/meilisearch/sdk/Client.java @@ -3,178 +3,67 @@ */ package com.meilisearch.sdk; -import com.google.gson.Gson; +import com.meilisearch.sdk.api.documents.DocumentHandler; +import com.meilisearch.sdk.api.index.IndexHandler; +import com.meilisearch.sdk.api.instance.InstanceHandler; +import com.meilisearch.sdk.api.keys.KeysHandler; -import com.meilisearch.sdk.exceptions.MeiliSearchApiException; +import java.util.Map; +import java.util.stream.Collectors; /** * MeiliSearch client */ public class Client { - public Config config; - public IndexesHandler indexesHandler; - public Gson gson; - public DumpHandler dumpHandler; + private final IndexHandler indexHandler; + private final InstanceHandler instanceHandler; + private final KeysHandler keysHandler; + private final Map> handlerMap; + private final ServiceTemplate serviceTemplate; - /** - * Calls instance for MeiliSearch client - * - * @param config Configuration to connect to MeiliSearch instance - */ - public Client(Config config) { - this.config = config; - this.gson = new Gson(); - this.indexesHandler = new IndexesHandler(config); - this.dumpHandler = new DumpHandler(config); + Client(Config config, ServiceTemplate serviceTemplate) { + this.serviceTemplate = serviceTemplate; + this.indexHandler = new IndexHandler(serviceTemplate, serviceTemplate.getRequestFactory()); + this.instanceHandler = new InstanceHandler(serviceTemplate, serviceTemplate.getRequestFactory()); + this.keysHandler = new KeysHandler(serviceTemplate, serviceTemplate.getRequestFactory()); + this.handlerMap = config.getModelMapping() + .entrySet() + .stream() + .collect( + Collectors.toMap( + Map.Entry::getKey, + entry -> new DocumentHandler<>(serviceTemplate, serviceTemplate.getRequestFactory(), entry.getKey(), entry.getValue()) + ) + ); } - /** - * Creates index - * Refer https://docs.meilisearch.com/reference/api/indexes.html#create-an-index - * - * @param uid Unique identifier for the index to create - * @return MeiliSearch API response - * @throws Exception if an error occurs - */ - public Index createIndex(String uid) throws Exception { - return this.createIndex(uid, null); + public IndexHandler index() { + return this.indexHandler; } - /** - * Creates index - * Refer https://docs.meilisearch.com/reference/api/indexes.html#create-an-index - * - * @param uid Unique identifier for the index to create - * @param primaryKey The primary key of the documents in that index - * @return MeiliSearch API response - * @throws Exception if an error occurs - */ - public Index createIndex(String uid, String primaryKey) throws Exception { - Index index = gson.fromJson(this.indexesHandler.create(uid, primaryKey), Index.class); - index.setConfig(this.config); - return index; + @SuppressWarnings("unchecked") + public DocumentHandler documents(String uid) { + return (DocumentHandler) this.handlerMap.get(uid); } - /** - * Gets all indexes - * Refer https://docs.meilisearch.com/reference/api/indexes.html#list-all-indexes - * - * @return list of indexes in the MeiliSearch client - * @throws Exception if an error occurs - */ - public Index[] getIndexList() throws Exception { - Index[] meiliSearchIndexList = gson.fromJson(this.indexesHandler.getAll(), Index[].class); - for (Index indexes : meiliSearchIndexList) { - indexes.setConfig(this.config); - } - return meiliSearchIndexList; - } - - /** - * Creates a local reference to an index identified by `uid`, without doing an HTTP call. - * Calling this method doesn't create an index by itself, but grants access to all the other methods in the Index class. - * - * @param uid Unique identifier of the index - * @return Index instance - * @throws Exception if an error occurs - */ - public Index index(String uid) throws Exception { - Index index = new Index(); - index.uid = uid; - index.setConfig(this.config); - return index; - } - - /** - * Gets single index by uid - * Refer https://docs.meilisearch.com/reference/api/indexes.html#get-one-index - * - * @param uid Unique identifier of the index to get - * @return MeiliSearch API response - * @throws Exception if an error occurs - */ - public Index getIndex(String uid) throws Exception { - Index indexes = gson.fromJson(this.indexesHandler.get(uid), Index.class); - indexes.setConfig(this.config); - return indexes; - } - - /** - * Updates single index by uid - * Refer https://docs.meilisearch.com/reference/api/indexes.html#update-an-index - * - * @param uid Unique identifier of the index to update - * @param primaryKey Primary key of the documents in the index - * @return MeiliSearch API response - * @throws Exception if an error occurs - */ - public Index updateIndex(String uid, String primaryKey) throws Exception { - Index index = gson.fromJson(this.indexesHandler.updatePrimaryKey(uid, primaryKey), Index.class); - index.setConfig(this.config); - return index; - } - - /** - * Deletes single index by uid - * Refer https://docs.meilisearch.com/reference/api/indexes.html#get-one-index - * - * @param uid Unique identifier of the index to delete - * @return MeiliSearch API response - * @throws Exception if an error occurs - */ - public String deleteIndex(String uid) throws Exception { - return this.indexesHandler.delete(uid); - } - - /** - * Gets single index by uid or if it does not exists, Create index - * - * @param uid Unique identifier for the index to create - * @param primaryKey The primary key of the documents in that index - * @return Index instance - * @throws Exception if an error occurs - */ - public Index getOrCreateIndex(String uid, String primaryKey) throws Exception { - try { - return this.getIndex(uid); - } catch (MeiliSearchApiException e) { - if (e.getErrorCode().equals("index_not_found")) { - return this.createIndex(uid, primaryKey); + public DocumentHandler documents(String uid, Class model) { + DocumentHandler handler = documents(uid); + if (handler != null) { + if (handler.getIndexModel() == model) { + return handler; } - throw e; } - } + handler = new DocumentHandler<>(serviceTemplate, serviceTemplate.getRequestFactory(), uid, model); + handlerMap.put(uid, handler); - /** - * Gets single index by uid or if it does not exists, Create index - * - * @param uid Unique identifier for the index to create - * @return Index instance - * @throws Exception if an error occurs - */ - public Index getOrCreateIndex(String uid) throws Exception { - return getOrCreateIndex(uid, null); + return handler; } - /** - * Triggers the creation of a MeiliSearch dump. - * Refer https://docs.meilisearch.com/reference/api/dump.html#create-a-dump - * - * @throws Exception if an error occurs - */ - public Dump createDump() throws Exception { - return this.dumpHandler.createDump(); + public InstanceHandler instance() { + return instanceHandler; } - /** - * Gets the status of a MeiliSearch dump. - * https://docs.meilisearch.com/reference/api/dump.html#get-dump-status - * - * @param uid Unique identifier for correspondent dump - * @return String with dump status - * @throws Exception if an error occurs - */ - public String getDumpStatus(String uid) throws Exception { - return this.dumpHandler.getDumpStatus(uid); + public KeysHandler keys() { + return keysHandler; } } diff --git a/src/main/java/com/meilisearch/sdk/ClientBuilder.java b/src/main/java/com/meilisearch/sdk/ClientBuilder.java new file mode 100644 index 00000000..60d87d99 --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/ClientBuilder.java @@ -0,0 +1,105 @@ +package com.meilisearch.sdk; + +import com.meilisearch.sdk.http.AbstractHttpClient; +import com.meilisearch.sdk.http.ApacheHttpClient; +import com.meilisearch.sdk.http.CustomOkHttpClient; +import com.meilisearch.sdk.http.DefaultHttpClient; +import com.meilisearch.sdk.http.factory.BasicRequestFactory; +import com.meilisearch.sdk.http.factory.RequestFactory; +import com.meilisearch.sdk.json.GsonJsonHandler; +import com.meilisearch.sdk.json.JacksonJsonHandler; +import com.meilisearch.sdk.json.JsonHandler; +import com.meilisearch.sdk.json.JsonbJsonHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ClientBuilder { + private static final Logger log = LoggerFactory.getLogger(ClientBuilder.class); + private final Config config; + private ServiceTemplate serviceTemplate; + private AbstractHttpClient httpClient; + private JsonHandler jsonHandler; + private RequestFactory requestFactory; + + private ClientBuilder(Config config) { + this.config = config; + } + + public static ClientBuilder withConfig(Config config) { + return new ClientBuilder(config); + } + + public ClientBuilder withServiceTemplate(ServiceTemplate serviceTemplate) { + this.serviceTemplate = serviceTemplate; + return this; + } + + public ClientBuilder withAutodetectHttpClient() { + try { + Class.forName("org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient", false, null); + this.httpClient = new ApacheHttpClient(config); + return this; + } catch (ClassNotFoundException e) {/* noop */} + try { + Class.forName("okhttp3.OkHttpClient", false, null); + this.httpClient = new CustomOkHttpClient(config); + return this; + } catch (ClassNotFoundException e) {/* noop */} + this.httpClient = new DefaultHttpClient(config); + return this; + } + + public ClientBuilder withHttpClient(AbstractHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public ClientBuilder withAutodetectJsonHandler() { + try { + Class.forName("com.google.gson.Gson", false, null); + this.jsonHandler = new GsonJsonHandler(); + return this; + } catch (ClassNotFoundException e) {/* noop */} + try { + Class.forName("com.fasterxml.jackson.databind.ObjectMapper", false, null); + this.jsonHandler = new JacksonJsonHandler(); + return this; + } catch (ClassNotFoundException e) {/* noop */} + try { + Class.forName("javax.json.bind.Jsonb", false, null); + this.jsonHandler = new JsonbJsonHandler(); + return this; + } catch (ClassNotFoundException e) {/* noop */} + throw new RuntimeException("No suitable json library found in classpath"); + } + + public ClientBuilder withJsonHandler(JsonHandler jsonHandler) { + this.jsonHandler = jsonHandler; + return this; + } + + public ClientBuilder withRequestFactory(RequestFactory requestFactory) { + this.requestFactory = requestFactory; + return this; + } + + public Client build() { + if (serviceTemplate != null && (jsonHandler != null || httpClient != null)) { + log.error("A ServiceTemplate is set while a JsonHandler and/or a HttpClient is set too. JsonHandler and HttpClient will be ignored!"); + } + if (this.jsonHandler == null) { + this.withAutodetectJsonHandler(); + } + if (this.httpClient == null) { + this.withAutodetectHttpClient(); + } + if (this.requestFactory == null) { + this.requestFactory = new BasicRequestFactory(this.jsonHandler,this.config); + } + if (serviceTemplate == null) { + this.serviceTemplate = new GenericServiceTemplate(this.httpClient, this.jsonHandler, this.requestFactory); + } + + return new Client(this.config, this.serviceTemplate); + } +} diff --git a/src/main/java/com/meilisearch/sdk/Config.java b/src/main/java/com/meilisearch/sdk/Config.java index f2065986..e2953729 100644 --- a/src/main/java/com/meilisearch/sdk/Config.java +++ b/src/main/java/com/meilisearch/sdk/Config.java @@ -1,11 +1,15 @@ package com.meilisearch.sdk; +import java.util.Collections; +import java.util.Map; + /** * MeiliSearch configuration */ public class Config { - String hostUrl; - String apiKey; + private final String hostUrl; + private final String apiKey; + private Map> modelMapping; /** * Creates a configuration without an API key @@ -27,8 +31,22 @@ public Config(String hostUrl, String apiKey) { this.apiKey = apiKey; } + /** + * Create a configuration with an API key + * + * @param hostUrl URL of the Meilisearch instance + * @param apiKey API key to pass to the header of requests sent to Meilisearch + * @param modelMapping Mapping of indexname to class + */ + public Config(String hostUrl, String apiKey, Map> modelMapping) { + this.hostUrl = hostUrl; + this.apiKey = apiKey; + this.modelMapping = Collections.unmodifiableMap(modelMapping); + } + /** * Method for returning the hostUrl + * * @return host URL string of the MeiliSearch instance */ public String getHostUrl() { @@ -37,9 +55,14 @@ public String getHostUrl() { /** * Method for returning the apiKey + * * @return API key String */ public String getApiKey() { return apiKey; } + + public Map> getModelMapping() { + return modelMapping; + } } diff --git a/src/main/java/com/meilisearch/sdk/MeiliSearchHttpRequest.java b/src/main/java/com/meilisearch/sdk/MeiliSearchHttpRequest.java index dc707c96..ef8299a0 100644 --- a/src/main/java/com/meilisearch/sdk/MeiliSearchHttpRequest.java +++ b/src/main/java/com/meilisearch/sdk/MeiliSearchHttpRequest.java @@ -28,7 +28,7 @@ class MeiliSearchHttpRequest { protected MeiliSearchHttpRequest(Config config) { this.client = new DefaultHttpClient(config); this.jsonHandler = new GsonJsonHandler(); - this.factory = new BasicRequestFactory(jsonHandler); + this.factory = new BasicRequestFactory(jsonHandler, config); } /** diff --git a/src/main/java/com/meilisearch/sdk/api/documents/DocumentHandler.java b/src/main/java/com/meilisearch/sdk/api/documents/DocumentHandler.java index ce1174da..edeefe66 100644 --- a/src/main/java/com/meilisearch/sdk/api/documents/DocumentHandler.java +++ b/src/main/java/com/meilisearch/sdk/api/documents/DocumentHandler.java @@ -6,7 +6,11 @@ import com.meilisearch.sdk.http.request.HttpMethod; import java.util.Collections; +import java.util.Date; import java.util.List; +import java.util.concurrent.TimeoutException; +import java.util.function.Function; +import java.util.stream.Collectors; public class DocumentHandler { private final ServiceTemplate serviceTemplate; @@ -21,6 +25,10 @@ public DocumentHandler(ServiceTemplate serviceTemplate, RequestFactory requestFa this.indexModel = indexModel; } + public Class getIndexModel() { + return indexModel; + } + /** * Retrieve a document with a specific identifier * @@ -138,7 +146,6 @@ public Update updateDocuments(String data) throws MeiliSearchRuntimeException { ); } - /** * Add or update a document * @@ -184,6 +191,34 @@ public Update deleteDocuments() throws MeiliSearchRuntimeException { ); } + /** + * @param data a list of model to delete + * @return an Update object with the updateId + * @throws MeiliSearchRuntimeException in case something went wrong (http error, json exceptions, etc) + */ + public Update deleteDocuments(List data) throws MeiliSearchRuntimeException { + String requestQuery = "/indexes/" + indexName + "/documents/delete-batch"; + return serviceTemplate.execute( + requestFactory.create(HttpMethod.DELETE, requestQuery, Collections.emptyMap(), null), + Update.class + ); + } + + /** + * @param data a list of model to delete + * @param uidResolverFunc a function to resolve the id + * @return an Update object with the updateId + * @throws MeiliSearchRuntimeException in case something went wrong (http error, json exceptions, etc) + */ + public Update deleteDocuments(List data, Function uidResolverFunc) throws MeiliSearchRuntimeException { + List documentsToDelete = data.stream().map(uidResolverFunc).collect(Collectors.toList()); + String requestQuery = "/indexes/" + indexName + "/documents/delete-batch"; + return serviceTemplate.execute( + requestFactory.create(HttpMethod.DELETE, requestQuery, Collections.emptyMap(), documentsToDelete), + Update.class + ); + } + /** * @param q the Querystring * @return a SearchResponse with the Hits represented by the mapped Class for this index @@ -250,4 +285,41 @@ public List getUpdates() throws MeiliSearchRuntimeException { Update.class ); } + + /** + * Waits for a pending update to be processed + * + * @param updateId ID of the index update + * @throws TimeoutException if timeout is reached + */ + public void waitForPendingUpdate(int updateId) throws TimeoutException { + this.waitForPendingUpdate(updateId, 5000, 50); + } + + /** + * Waits for a pending update to be processed + * + * @param updateId ID of the index update + * @param timeoutInMs number of milliseconds before throwing an Exception + * @param intervalInMs number of milliseconds before requesting the status again + * @throws TimeoutException if timeout is reached + */ + public void waitForPendingUpdate(int updateId, int timeoutInMs, int intervalInMs) throws TimeoutException { + Update update = new Update(); + long startTime = new Date().getTime(); + long elapsedTime = 0; + + while (!"processed".equalsIgnoreCase(update.getStatus())) { + if (elapsedTime >= timeoutInMs) { + throw new TimeoutException(); + } + update = this.getUpdate(updateId); + try { + Thread.sleep(intervalInMs); + } catch (InterruptedException e) { + throw new TimeoutException(); + } + elapsedTime = new Date().getTime() - startTime; + } + } } diff --git a/src/main/java/com/meilisearch/sdk/api/documents/SearchRequest.java b/src/main/java/com/meilisearch/sdk/api/documents/SearchRequest.java index 1aaf2507..f5cfb848 100644 --- a/src/main/java/com/meilisearch/sdk/api/documents/SearchRequest.java +++ b/src/main/java/com/meilisearch/sdk/api/documents/SearchRequest.java @@ -4,15 +4,15 @@ import java.util.List; public class SearchRequest { - private final String q; - private final int offset; - private final int limit; - private final String filters; - private final List attributesToRetrieve; - private final List attributesToCrop; - private final int cropLength; - private final List attributesToHighlight; - private final boolean matches; + private String q; + private int offset; + private int limit; + private String filters; + private List attributesToRetrieve; + private List attributesToCrop; + private int cropLength; + private List attributesToHighlight; + private boolean matches; public SearchRequest(String q) { this(q, 0); @@ -85,4 +85,49 @@ public String getFilters() { public boolean isMatches() { return matches; } + + public SearchRequest setQ(String q) { + this.q = q; + return this; + } + + public SearchRequest setOffset(int offset) { + this.offset = offset; + return this; + } + + public SearchRequest setLimit(int limit) { + this.limit = limit; + return this; + } + + public SearchRequest setFilters(String filters) { + this.filters = filters; + return this; + } + + public SearchRequest setAttributesToRetrieve(List attributesToRetrieve) { + this.attributesToRetrieve = attributesToRetrieve; + return this; + } + + public SearchRequest setAttributesToCrop(List attributesToCrop) { + this.attributesToCrop = attributesToCrop; + return this; + } + + public SearchRequest setCropLength(int cropLength) { + this.cropLength = cropLength; + return this; + } + + public SearchRequest setAttributesToHighlight(List attributesToHighlight) { + this.attributesToHighlight = attributesToHighlight; + return this; + } + + public SearchRequest setMatches(boolean matches) { + this.matches = matches; + return this; + } } diff --git a/src/main/java/com/meilisearch/sdk/api/index/IndexHandler.java b/src/main/java/com/meilisearch/sdk/api/index/IndexHandler.java index f039a9db..c5f82eff 100644 --- a/src/main/java/com/meilisearch/sdk/api/index/IndexHandler.java +++ b/src/main/java/com/meilisearch/sdk/api/index/IndexHandler.java @@ -2,6 +2,7 @@ import com.meilisearch.sdk.ServiceTemplate; import com.meilisearch.sdk.api.documents.Update; +import com.meilisearch.sdk.api.instance.IndexStats; import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; import com.meilisearch.sdk.http.factory.RequestFactory; import com.meilisearch.sdk.http.request.HttpMethod; @@ -129,4 +130,37 @@ public Update updateSettings(String index, Settings settings) throws MeiliSearch public Update resetSettings(String index) throws MeiliSearchRuntimeException { return settingsHandler.resetSettings(index); } + + + /** + * Get Index Stats + * Refer https://docs.meilisearch.com/reference/api/stats.html#get-stat-of-an-index + * + * @param index the index name + * @return Index Stats + * @throws MeiliSearchRuntimeException if something goes wrong + */ + public IndexStats getStats(String index) { + String requestQuery = "/indexes/" + index + "/stats"; + return serviceTemplate.execute( + requestFactory.create(HttpMethod.GET, requestQuery, Collections.emptyMap(), null), + IndexStats.class + ); + } + + /** + * Gets single index by uid or if it does not exists, Create index + * + * @param uid Unique identifier for the index to create + * @param primaryKey The primary key of the documents in that index + * @return Index instance + * @throws MeiliSearchRuntimeException if an error occurs + */ + public Index getOrCreateIndex(String uid, String primaryKey) { + try { + return this.getIndex(uid); + } catch (MeiliSearchRuntimeException e) { + return this.createIndex(uid, primaryKey); + } + } } diff --git a/src/main/java/com/meilisearch/sdk/api/index/Settings.java b/src/main/java/com/meilisearch/sdk/api/index/Settings.java index b3930364..50833904 100644 --- a/src/main/java/com/meilisearch/sdk/api/index/Settings.java +++ b/src/main/java/com/meilisearch/sdk/api/index/Settings.java @@ -1,7 +1,5 @@ package com.meilisearch.sdk.api.index; -import com.meilisearch.sdk.Index; - import java.util.HashMap; import java.util.Map; @@ -11,7 +9,7 @@ * Refer https://docs.meilisearch.com/references/settings.html */ public class Settings { - private HashMap synonyms; + private HashMap synonyms = new HashMap<>(); private String[] stopWords; private String[] rankingRules; private String[] attributesForFaceting; diff --git a/src/main/java/com/meilisearch/sdk/api/instance/Dump.java b/src/main/java/com/meilisearch/sdk/api/instance/Dump.java new file mode 100644 index 00000000..1091a01e --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/api/instance/Dump.java @@ -0,0 +1,22 @@ +package com.meilisearch.sdk.api.instance; + +public class Dump { + private String status; + private String uid; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } +} diff --git a/src/main/java/com/meilisearch/sdk/api/instance/IndexStats.java b/src/main/java/com/meilisearch/sdk/api/instance/IndexStats.java index eb514586..a19135ec 100644 --- a/src/main/java/com/meilisearch/sdk/api/instance/IndexStats.java +++ b/src/main/java/com/meilisearch/sdk/api/instance/IndexStats.java @@ -24,11 +24,11 @@ public void setNumberOfDocuments(int numberOfDocuments) { this.numberOfDocuments = numberOfDocuments; } - public boolean isIndexing() { + public boolean getIsIndexing() { return isIndexing; } - public void setIndexing(boolean indexing) { + public void setIsIndexing(boolean indexing) { isIndexing = indexing; } diff --git a/src/main/java/com/meilisearch/sdk/api/instance/InstanceHandler.java b/src/main/java/com/meilisearch/sdk/api/instance/InstanceHandler.java index f5a5c14f..21c771c5 100644 --- a/src/main/java/com/meilisearch/sdk/api/instance/InstanceHandler.java +++ b/src/main/java/com/meilisearch/sdk/api/instance/InstanceHandler.java @@ -19,6 +19,8 @@ public InstanceHandler(ServiceTemplate serviceTemplate, RequestFactory requestFa } /** + * Refer https://docs.meilisearch.com/reference/api/health.html + * * @return a map with health status of MeiliSearch */ public Map health() { @@ -41,6 +43,8 @@ public boolean isHealthy() { } /** + * Refer https://docs.meilisearch.com/reference/api/stats.html + * * @return a map with version information of Meilisearch */ public Map getVersion() { @@ -73,4 +77,35 @@ public Stats getStats() { ); } + + /** + * Creates a dump + * Refer https://docs.meilisearch.com/references/dump.html#create-a-dump + * + * @return Dump status + * @throws MeiliSearchRuntimeException if something goes wrong + */ + public Dump createDump() { + String requestQuery = "/dumps"; + return serviceTemplate.execute( + requestFactory.create(HttpMethod.POST, requestQuery, Collections.emptyMap(), null), + Dump.class + ); + } + + /** + * Gets dump status + * Refer https://docs.meilisearch.com/references/dump.html#get-dump-status + * + * @param uid Unique identifier for correspondent dump + * @return dump status + * @throws MeiliSearchRuntimeException if something goes wrong + */ + public Dump getDumpStatus(String uid) { + String requestQuery = "/dumps/" + uid + "/status"; + return serviceTemplate.execute( + requestFactory.create(HttpMethod.GET, requestQuery, Collections.emptyMap(), null), + Dump.class + ); + } } diff --git a/src/main/java/com/meilisearch/sdk/http/ApacheHttpClient.java b/src/main/java/com/meilisearch/sdk/http/ApacheHttpClient.java index 3c3be551..148ab3fd 100644 --- a/src/main/java/com/meilisearch/sdk/http/ApacheHttpClient.java +++ b/src/main/java/com/meilisearch/sdk/http/ApacheHttpClient.java @@ -9,6 +9,7 @@ import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; import org.apache.hc.client5.http.async.methods.SimpleRequestProducer; import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer; +import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; import org.apache.hc.client5.http.impl.async.HttpAsyncClients; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.concurrent.FutureCallback; @@ -34,9 +35,11 @@ public ApacheHttpClient(Config config) { .setSoTimeout(Timeout.ofSeconds(5)) .build(); - this.client = HttpAsyncClients.custom() + CloseableHttpAsyncClient build = HttpAsyncClients.custom() .setIOReactorConfig(ioReactorConfig) .build(); + build.start(); + this.client = build; } public ApacheHttpClient(Config config, HttpAsyncClient client) { diff --git a/src/main/java/com/meilisearch/sdk/http/factory/BasicRequestFactory.java b/src/main/java/com/meilisearch/sdk/http/factory/BasicRequestFactory.java index f266c350..cd54cd79 100644 --- a/src/main/java/com/meilisearch/sdk/http/factory/BasicRequestFactory.java +++ b/src/main/java/com/meilisearch/sdk/http/factory/BasicRequestFactory.java @@ -1,5 +1,6 @@ package com.meilisearch.sdk.http.factory; +import com.meilisearch.sdk.Config; import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; import com.meilisearch.sdk.http.request.BasicHttpRequest; import com.meilisearch.sdk.http.request.HttpMethod; @@ -10,15 +11,17 @@ public class BasicRequestFactory implements RequestFactory { private final JsonHandler jsonHandler; + private final Config config; - public BasicRequestFactory(JsonHandler jsonHandler) { + public BasicRequestFactory(JsonHandler jsonHandler, Config config) { this.jsonHandler = jsonHandler; + this.config = config; } @Override public HttpRequest create(HttpMethod method, String path, Map headers, T content) { try { - return new BasicHttpRequest(method, path, headers, content == null ? null : this.jsonHandler.encode(content)); + return new BasicHttpRequest(method, config.getHostUrl() + path, headers, content == null ? null : this.jsonHandler.encode(content)); } catch (Exception e) { throw new MeiliSearchRuntimeException(e); } diff --git a/src/main/java/com/meilisearch/sdk/json/GsonJsonHandler.java b/src/main/java/com/meilisearch/sdk/json/GsonJsonHandler.java index f0593447..20e58f28 100644 --- a/src/main/java/com/meilisearch/sdk/json/GsonJsonHandler.java +++ b/src/main/java/com/meilisearch/sdk/json/GsonJsonHandler.java @@ -2,6 +2,7 @@ import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; +import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; public class GsonJsonHandler implements JsonHandler { private final Gson gson; @@ -16,14 +17,14 @@ public GsonJsonHandler(Gson gson) { @Override public String encode(Object o) throws Exception { - if (o.getClass() == String.class) { + if (o != null && o.getClass() == String.class) { return (String) o; } try { return gson.toJson(o); } catch (Exception e) { // todo: use dedicated exception - throw new RuntimeException("Error while serializing: ", e); + throw new MeiliSearchRuntimeException(e); } } @@ -32,7 +33,7 @@ public String encode(Object o) throws Exception { public T decode(Object o, Class targetClass, Class... parameters) throws Exception { if (o == null) { // todo: use dedicated exception - throw new RuntimeException("String to deserialize is null"); + throw new MeiliSearchRuntimeException(); } if (targetClass == String.class) { return (T) o; @@ -46,7 +47,7 @@ public T decode(Object o, Class targetClass, Class... parameters) thro } } catch (Exception e) { // todo: use dedicated exception - throw new RuntimeException("Error while deserializing: ", e); + throw new MeiliSearchRuntimeException(e); } } } diff --git a/src/test/java/com/meilisearch/integration/ClientTest.java b/src/test/java/com/meilisearch/integration/ClientTest.java index c3fee595..7ba7db88 100644 --- a/src/test/java/com/meilisearch/integration/ClientTest.java +++ b/src/test/java/com/meilisearch/integration/ClientTest.java @@ -2,8 +2,8 @@ import com.meilisearch.integration.classes.AbstractIT; import com.meilisearch.integration.classes.TestData; -import com.meilisearch.sdk.Dump; -import com.meilisearch.sdk.Index; +import com.meilisearch.sdk.api.index.Index; +import com.meilisearch.sdk.api.instance.Dump; import com.meilisearch.sdk.utils.Movie; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; @@ -14,7 +14,7 @@ import static org.junit.jupiter.api.Assertions.*; -import com.meilisearch.sdk.exceptions.MeiliSearchApiException; +import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; @Tag("integration") public class ClientTest extends AbstractIT { @@ -40,10 +40,10 @@ static void cleanMeiliSearch() { @Test public void testCreateIndexWithoutPrimaryKey() throws Exception { String indexUid = "CreateIndexWithoutPrimaryKey"; - Index index = client.createIndex(indexUid); + Index index = client.index().createIndex(indexUid); assertEquals(index.getUid(), indexUid); assertNull(index.getPrimaryKey()); - client.deleteIndex(index.getUid()); + client.index().deleteIndex(index.getUid()); } /** @@ -52,32 +52,32 @@ public void testCreateIndexWithoutPrimaryKey() throws Exception { @Test public void testCreateIndexWithPrimaryKey() throws Exception { String indexUid = "CreateIndexWithPrimaryKey"; - Index index = client.createIndex(indexUid, this.primaryKey); + Index index = client.index().createIndex(indexUid, this.primaryKey); assertEquals(index.getUid(), indexUid); assertEquals(index.getPrimaryKey(), this.primaryKey); - client.deleteIndex(index.getUid()); + client.index().deleteIndex(index.getUid()); } @Test public void testCreateIndexWithPrimaryKeyIfIndexDoesNotExists() throws Exception { String indexUid = "dummyIndexUid"; - Index index = client.getOrCreateIndex(indexUid, this.primaryKey); + Index index = client.index().getOrCreateIndex(indexUid, this.primaryKey); assertEquals(index.getUid(), indexUid); assertEquals(index.getPrimaryKey(), this.primaryKey); - client.deleteIndex(index.getUid()); + client.index().deleteIndex(index.getUid()); } @Test public void testGetIndexWithPrimaryKeyIfIndexAlreadyExists() throws Exception { String indexUid = "dummyIndexUid"; - Index createdIndex = client.getOrCreateIndex(indexUid, this.primaryKey); + Index createdIndex = client.index().getOrCreateIndex(indexUid, this.primaryKey); assertEquals(createdIndex.getUid(), indexUid); - Index retrievedIndex = client.getOrCreateIndex(indexUid, this.primaryKey); + Index retrievedIndex = client.index().getOrCreateIndex(indexUid, this.primaryKey); assertEquals(retrievedIndex.getUid(), indexUid); assertEquals(createdIndex.getUid(), retrievedIndex.getUid()); - client.deleteIndex(createdIndex.getUid()); + client.index().deleteIndex(createdIndex.getUid()); } @Test @@ -85,13 +85,13 @@ public void testGetOrCreateIndexShouldNotThrowAnyException() throws Exception { String indexUid = "dummyIndexUid"; Index createdIndex = null; try { - createdIndex = client.getOrCreateIndex(indexUid, this.primaryKey); - Index retrievedIndex = client.getOrCreateIndex(indexUid, this.primaryKey); + createdIndex = client.index().getOrCreateIndex(indexUid, this.primaryKey); + Index retrievedIndex = client.index().getOrCreateIndex(indexUid, this.primaryKey); } catch (Exception e) { - client.deleteIndex(createdIndex.getUid()); + client.index().deleteIndex(createdIndex.getUid()); fail("Should Not Throw Any Exception"); } - client.deleteIndex(createdIndex.getUid()); + client.index().deleteIndex(createdIndex.getUid()); } /** @@ -100,14 +100,14 @@ public void testGetOrCreateIndexShouldNotThrowAnyException() throws Exception { @Test public void testCreateIndexAlreadyExists() throws Exception { String indexUid = "CreateIndexAlreadyExists"; - Index index = client.createIndex(indexUid, this.primaryKey); + Index index = client.index().createIndex(indexUid, this.primaryKey); assertEquals(index.getUid(), indexUid); assertEquals(index.getPrimaryKey(), this.primaryKey); assertThrows( - MeiliSearchApiException.class, - () -> client.createIndex(indexUid, this.primaryKey) + MeiliSearchRuntimeException.class, + () -> client.index().createIndex(indexUid, this.primaryKey) ); - client.deleteIndex(index.getUid()); + client.index().deleteIndex(index.getUid()); } /** @@ -116,14 +116,14 @@ public void testCreateIndexAlreadyExists() throws Exception { @Test public void testUpdateIndexPrimaryKey() throws Exception { String indexUid = "UpdateIndexPrimaryKey"; - Index index = client.createIndex(indexUid); + Index index = client.index().createIndex(indexUid); assertEquals(index.getUid(), indexUid); assertNull(index.getPrimaryKey()); - index = client.updateIndex(indexUid, this.primaryKey); + index = client.index().updateIndex(indexUid, this.primaryKey); assertTrue(index instanceof Index); assertEquals(index.getUid(), indexUid); assertEquals(index.getPrimaryKey(), this.primaryKey); - client.deleteIndex(index.getUid()); + client.index().deleteIndex(index.getUid()); } /** @@ -132,11 +132,11 @@ public void testUpdateIndexPrimaryKey() throws Exception { @Test public void testGetIndex() throws Exception { String indexUid = "GetIndex"; - Index index = client.createIndex(indexUid); - Index getIndex = client.getIndex(indexUid); + Index index = client.index().createIndex(indexUid); + Index getIndex = client.index().getIndex(indexUid); assertEquals(index.getUid(), getIndex.getUid()); assertEquals(index.getPrimaryKey(), getIndex.getPrimaryKey()); - client.deleteIndex(index.getUid()); + client.index().deleteIndex(index.getUid()); } /** @@ -145,14 +145,14 @@ public void testGetIndex() throws Exception { @Test public void testGetIndexList() throws Exception { String[] indexUids = {"GetIndexList", "GetIndexList2"}; - Index index1 = client.createIndex(indexUids[0]); - Index index2 = client.createIndex(indexUids[1], this.primaryKey); - Index[] indexes = client.getIndexList(); + Index index1 = client.index().createIndex(indexUids[0]); + Index index2 = client.index().createIndex(indexUids[1], this.primaryKey); + Index[] indexes = client.index().getAllIndexes(); assertEquals(2, indexes.length); assert (Arrays.asList(indexUids).contains(indexUids[0])); assert (Arrays.asList(indexUids).contains(indexUids[1])); - client.deleteIndex(indexUids[0]); - client.deleteIndex(indexUids[1]); + client.index().deleteIndex(indexUids[0]); + client.index().deleteIndex(indexUids[1]); } /** @@ -161,11 +161,11 @@ public void testGetIndexList() throws Exception { @Test public void testDeleteIndex() throws Exception { String indexUid = "DeleteIndex"; - Index index = client.createIndex(indexUid); - client.deleteIndex(index.getUid()); + Index index = client.index().createIndex(indexUid); + client.index().deleteIndex(index.getUid()); assertThrows( - MeiliSearchApiException.class, - () -> client.getIndex(indexUid) + MeiliSearchRuntimeException.class, + () -> client.index().getIndex(indexUid) ); } @@ -175,11 +175,9 @@ public void testDeleteIndex() throws Exception { @Test public void testIndexMethodCallInexistentIndex() throws Exception { String indexUid = "IndexMethodCallInexistentIndex"; - Index index = client.index(indexUid); - assertEquals(indexUid, index.getUid()); assertThrows( - MeiliSearchApiException.class, - () -> client.getIndex(indexUid) + MeiliSearchRuntimeException.class, + () -> client.index().getIndex(indexUid) ); } @@ -189,8 +187,8 @@ public void testIndexMethodCallInexistentIndex() throws Exception { @Test public void testIndexMethodCallExistingIndex() throws Exception { String indexUid = "IndexMethodCallExistingIndex"; - Index createdIndex = client.createIndex(indexUid); - Index index = client.index(indexUid); + Index createdIndex = client.index().createIndex(indexUid); + Index index = client.index().getIndex(indexUid); assertEquals(createdIndex.getUid(), index.getUid()); assertEquals(null, index.getPrimaryKey()); } @@ -202,11 +200,9 @@ public void testIndexMethodCallExistingIndex() throws Exception { public void testIndexMethodCallExistingIndexWithPrimaryKey() throws Exception { String indexUid = "IndexMethodCallExistingIndexWithPrimaryKey"; String primaryKey = "PrimaryKey"; - Index createdIndex = client.createIndex(indexUid, primaryKey); - Index index = client.index(indexUid); + Index createdIndex = client.index().createIndex(indexUid, primaryKey); + Index index = client.index().getIndex(indexUid); assertEquals(createdIndex.getUid(), index.getUid()); - assertEquals(null, index.getPrimaryKey()); - index.fetchPrimaryKey(); assertEquals(primaryKey, index.getPrimaryKey()); } @@ -215,7 +211,7 @@ public void testIndexMethodCallExistingIndexWithPrimaryKey() throws Exception { */ @Test public void testCreateDump() throws Exception { - Dump dump = client.createDump(); + Dump dump = client.instance().createDump(); String status = dump.getStatus(); assertEquals(status, "in_progress"); } @@ -225,9 +221,9 @@ public void testCreateDump() throws Exception { */ @Test public void testGetDumpStatus() throws Exception { - Dump dump = client.createDump(); + Dump dump = client.instance().createDump(); String uid = dump.getUid(); - String status = client.getDumpStatus(uid); + Dump status = client.instance().getDumpStatus(uid); assertNotNull(status); assertNotNull(uid); } diff --git a/src/test/java/com/meilisearch/integration/DocumentsTest.java b/src/test/java/com/meilisearch/integration/DocumentsTest.java index 5a69163b..af54f8ef 100644 --- a/src/test/java/com/meilisearch/integration/DocumentsTest.java +++ b/src/test/java/com/meilisearch/integration/DocumentsTest.java @@ -2,8 +2,10 @@ import com.meilisearch.integration.classes.AbstractIT; import com.meilisearch.integration.classes.TestData; -import com.meilisearch.sdk.Index; -import com.meilisearch.sdk.UpdateStatus; +import com.meilisearch.sdk.api.documents.DocumentHandler; +import com.meilisearch.sdk.api.documents.Update; +import com.meilisearch.sdk.api.index.Index; +import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; import com.meilisearch.sdk.utils.Movie; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.AfterAll; @@ -13,12 +15,12 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.concurrent.TimeoutException; import static org.junit.jupiter.api.Assertions.*; -import com.meilisearch.sdk.exceptions.MeiliSearchApiException; - @Tag("integration") public class DocumentsTest extends AbstractIT { @@ -39,19 +41,16 @@ static void cleanMeiliSearch() { public void testAddDocumentsSingle() throws Exception { String indexUid = "AddDocumentsSingle"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid,""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - String singleDocument = this.gson.toJson(testData.getData().get(0)); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments("[" + singleDocument + "]"), - UpdateStatus.class - ); + Movie singleDocument = testData.getData().get(0); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(Collections.singletonList(singleDocument)); + movieHandler.waitForPendingUpdate(update.getUpdateId()); + Movie[] movies = movieHandler.getDocuments().toArray(new Movie[0]); - index.waitForPendingUpdate(updateInfo.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); - - assertEquals(1, movies.length); + assertEquals(20, movies.length); assertEquals("419704", movies[0].getId()); assertEquals("Ad Astra", movies[0].getTitle()); assertEquals("https://image.tmdb.org/t/p/original/xBHvZcjRiWyobQ9kxBhO6B2dtRI.jpg", movies[0].getPoster()); @@ -71,16 +70,14 @@ public void testAddDocumentsSingle() throws Exception { public void testAddDocumentsMultiple() throws Exception { String indexUid = "AddDocumentsMultiple"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); - index.waitForPendingUpdate(updateInfo.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Movie[] movies = movieHandler.getDocuments().toArray(new Movie[0]); for (int i = 0; i < movies.length; i++) { assertEquals(movies[i].getTitle(), testData.getData().get(i).getTitle()); } @@ -93,27 +90,20 @@ public void testAddDocumentsMultiple() throws Exception { public void testUpdateDocument() throws Exception { String indexUid = "UpdateDocument"; - Index index = client.createIndex(indexUid); + Index index = client.index().createIndex(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); + Movie[] movies = movieHandler.getDocuments().toArray(new Movie[0]); Movie toUpdate = movies[0]; toUpdate.setTitle("The Perks of Being a Wallflower"); toUpdate.setOverview("The best movie I've ever seen"); - updateInfo = this.gson.fromJson( - index.updateDocuments("[" + this.gson.toJson(toUpdate) + "]"), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - Movie responseUpdate = this.gson.fromJson(index.getDocument(toUpdate.getId()), Movie.class); + update = movieHandler.updateDocuments(Collections.singletonList(toUpdate)); + movieHandler.waitForPendingUpdate(update.getUpdateId()); + Movie responseUpdate = movieHandler.getDocument(toUpdate.getId()); assertEquals(toUpdate.getTitle(), responseUpdate.getTitle()); assertEquals(toUpdate.getOverview(), responseUpdate.getOverview()); @@ -125,16 +115,13 @@ public void testUpdateDocument() throws Exception { @Test public void testUpdateDocuments() throws Exception { String indexUid = "UpdateDocuments"; - Index index = client.createIndex(indexUid); + Index index = client.index().createIndex(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); + Movie[] movies = movieHandler.getDocuments().toArray(new Movie[0]); List toUpdate = new ArrayList<>(); for (int i = 0; i < 5; i++) { movies[i].setTitle("Star wars episode: " + i); @@ -142,14 +129,12 @@ public void testUpdateDocuments() throws Exception { toUpdate.add(movies[i]); } - updateInfo = this.gson.fromJson( - index.updateDocuments(this.gson.toJson(toUpdate)), - UpdateStatus.class - ); + update = movieHandler.updateDocuments(toUpdate); + - index.waitForPendingUpdate(updateInfo.getUpdateId()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); for (int j = 0; j < 5; j++) { - Movie responseUpdate = this.gson.fromJson(index.getDocument(toUpdate.get(j).getId()), Movie.class); + Movie responseUpdate = movieHandler.getDocument(toUpdate.get(j).getId()); assertEquals(toUpdate.get(j).getTitle(), responseUpdate.getTitle()); assertEquals(toUpdate.get(j).getOverview(), responseUpdate.getOverview()); } @@ -162,19 +147,13 @@ public void testUpdateDocuments() throws Exception { public void testGetDocument() throws Exception { String indexUid = "GetDocument"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - Movie movie = this.gson.fromJson( - index.getDocument(testData.getData().get(0).getId()), - Movie.class - ); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); + Movie movie = movieHandler.getDocument(testData.getData().get(0).getId()); assertEquals(movie.getTitle(), testData.getData().get(0).getTitle()); } @@ -185,16 +164,13 @@ public void testGetDocument() throws Exception { public void testGetDocuments() throws Exception { String indexUid = "GetDocuments"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); + Movie[] movies = movieHandler.getDocuments().toArray(new Movie[0]); assertEquals(20, movies.length); for (int i = 0; i < movies.length; i++) { assertEquals(movies[i].getTitle(), testData.getData().get(i).getTitle()); @@ -215,16 +191,13 @@ public void testGetDocumentsLimit() throws Exception { String indexUid = "GetDocumentsLimit"; int limit = 24; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(limit), Movie[].class); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); + Movie[] movies = movieHandler.getDocuments(limit).toArray(new Movie[0]); assertEquals(limit, movies.length); for (int i = 0; i < movies.length; i++) { assertEquals(movies[i].getId(), testData.getData().get(i).getId()); @@ -238,26 +211,24 @@ public void testGetDocumentsLimit() throws Exception { public void testDeleteDocument() throws Exception { String indexUid = "DeleteDocument"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Movie[] movies = movieHandler.getDocuments().toArray(new Movie[0]); Movie toDelete = movies[0]; - updateInfo = this.gson.fromJson( - index.deleteDocument(toDelete.getId()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + update = movieHandler.deleteDocument(toDelete.getId()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); + + assertNotNull(toDelete); + assertNotNull(toDelete.getId()); assertThrows( - MeiliSearchApiException.class, - () -> index.getDocument(toDelete.getId()) + MeiliSearchRuntimeException.class, + () -> movieHandler.getDocument(toDelete.getId()) ); } @@ -268,27 +239,28 @@ public void testDeleteDocument() throws Exception { public void testDeleteDocuments() throws Exception { String indexUid = "DeleteDocuments"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Movie[] movies = movieHandler.getDocuments().toArray(new Movie[0]); assertEquals(20, movies.length); - List identifiersToDelete = getIdentifiersToDelete(movies); + List identifiersToDelete = getIdentifiersToDelete(movies); - updateInfo = this.gson.fromJson( - index.deleteDocuments(identifiersToDelete), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + identifiersToDelete.forEach(s -> { + try { + Update u = movieHandler.deleteDocument(s); + movieHandler.waitForPendingUpdate(u.getUpdateId()); + } catch (TimeoutException e) { + fail(e); + } + }); - movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + movies = movieHandler.getDocuments().toArray(new Movie[0]); boolean containsDeletedMovie = Arrays.stream(movies) @@ -312,25 +284,20 @@ private List getIdentifiersToDelete(Movie[] movies) { @Test public void testDeleteAllDocuments() throws Exception { String indexUid = "DeleteAllDocuments"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movieHandler = client.documents("movies"); + Update update = movieHandler.addDocuments(testData.getData()); + movieHandler.waitForPendingUpdate(update.getUpdateId()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Movie[] movies = movieHandler.getDocuments().toArray(new Movie[0]); assertEquals(20, movies.length); - updateInfo = this.gson.fromJson( - index.deleteAllDocuments(), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + update = movieHandler.deleteDocuments(); + movieHandler.waitForPendingUpdate(update.getUpdateId()); - movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + movies = movieHandler.getDocuments().toArray(new Movie[0]); assertEquals(0, movies.length); } diff --git a/src/test/java/com/meilisearch/integration/ExceptionsTest.java b/src/test/java/com/meilisearch/integration/ExceptionsTest.java index 3a354403..7aad8569 100644 --- a/src/test/java/com/meilisearch/integration/ExceptionsTest.java +++ b/src/test/java/com/meilisearch/integration/ExceptionsTest.java @@ -1,16 +1,21 @@ package com.meilisearch.integration; import com.meilisearch.integration.classes.AbstractIT; -import com.meilisearch.sdk.Index; +import com.meilisearch.sdk.api.index.Index; import com.meilisearch.sdk.exceptions.APIError; import com.meilisearch.sdk.exceptions.MeiliSearchApiException; -import org.junit.jupiter.api.*; +import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; @Tag("integration") public class ExceptionsTest extends AbstractIT { - + @BeforeEach public void initialize() { @@ -32,7 +37,7 @@ public void testErrorSerializeAndGetters() { String errorType = "authentication_error"; String errorLink = "https://docs.meilisearch.com/errors#missing_authorization_header"; try { - throw new MeiliSearchApiException(new APIError(errorMessage,errorCode,errorType,errorLink)); + throw new MeiliSearchApiException(new APIError(errorMessage, errorCode, errorType, errorLink)); } catch (MeiliSearchApiException e) { assertEquals(errorMessage, e.getMessage()); assertEquals(errorCode, e.getErrorCode()); @@ -45,17 +50,19 @@ public void testErrorSerializeAndGetters() { * Test MeiliSearchApiException is thrown on MeiliSearch bad request */ @Test - public void testMeiliSearchApiExceptionBadRequest () throws Exception { + public void testMeiliSearchApiExceptionBadRequest() throws Exception { String indexUid = "MeiliSearchApiExceptionBadRequest"; - Index index = client.createIndex(indexUid); + Index index = client.index().createIndex(indexUid); assertThrows( - MeiliSearchApiException.class, - () -> client.createIndex(indexUid) + MeiliSearchRuntimeException.class, + () -> client.index().createIndex(indexUid) ); try { - client.createIndex(indexUid); - } catch (MeiliSearchApiException e) { - assertEquals("index_already_exists", e.getErrorCode()); + client.index().createIndex(indexUid); + } catch (MeiliSearchRuntimeException e) { + if (e.getCause().getClass() == MeiliSearchApiException.class) { + assertEquals("index_already_exists", ((MeiliSearchApiException) e.getCause()).getErrorCode()); + } } } } diff --git a/src/test/java/com/meilisearch/integration/SearchTest.java b/src/test/java/com/meilisearch/integration/SearchTest.java index 5806b330..a525baf7 100644 --- a/src/test/java/com/meilisearch/integration/SearchTest.java +++ b/src/test/java/com/meilisearch/integration/SearchTest.java @@ -2,38 +2,32 @@ import com.meilisearch.integration.classes.AbstractIT; import com.meilisearch.integration.classes.TestData; +import com.meilisearch.sdk.api.documents.DocumentHandler; +import com.meilisearch.sdk.api.documents.SearchRequest; +import com.meilisearch.sdk.api.documents.SearchResponse; +import com.meilisearch.sdk.api.documents.Update; +import com.meilisearch.sdk.api.index.Index; import com.meilisearch.sdk.json.GsonJsonHandler; -import com.meilisearch.sdk.Index; -import com.meilisearch.sdk.UpdateStatus; -import com.meilisearch.sdk.SearchRequest; -import com.meilisearch.sdk.model.SearchResult; import com.meilisearch.sdk.utils.Movie; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; -import static org.hamcrest.CoreMatchers.instanceOf; +import java.util.Collections; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; @Tag("integration") public class SearchTest extends AbstractIT { private TestData testData; - final class Results { - Movie[] hits; - int offset; - int limit; - int nbHits; - boolean exhaustiveNbHits; - int processingTimeMs; - String query; - } - - @BeforeEach public void initialize() { this.setUp(); @@ -54,24 +48,22 @@ static void cleanMeiliSearch() { @Test public void testBasicSearch() throws Exception { String indexUid = "BasicSearch"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - - SearchResult searchResult = index.search("batman"); - - System.out.println(searchResult.getFacetsDistribution()); - assertEquals(1, searchResult.getHits().size()); - assertEquals(0, searchResult.getOffset()); - assertEquals(20, searchResult.getLimit()); - assertEquals(1, searchResult.getNbHits()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); + + SearchResponse res = movies.search("batman"); + assertEquals(1, res.getHits().size()); + assertEquals(0, res.getOffset()); + assertEquals(20, res.getLimit()); + assertFalse(res.isExhaustiveNbHits()); + assertEquals(1, res.getNbHits()); + assertNotEquals(0, res.getProcessingTimeMs()); + assertEquals("batman", res.getQuery()); } /** @@ -80,22 +72,18 @@ public void testBasicSearch() throws Exception { @Test public void testSearchOffset() throws Exception { String indexUid = "SearchOffset"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); SearchRequest searchRequest = new SearchRequest("a").setOffset(20); - SearchResult searchResult = index.search(searchRequest); - - assertEquals(10, searchResult.getHits().size()); - assertEquals(30, searchResult.getNbHits()); + SearchResponse search = movies.search(searchRequest); + assertEquals(10, search.getHits().size()); + assertEquals(30, search.getNbHits()); } /** @@ -104,58 +92,45 @@ public void testSearchOffset() throws Exception { @Test public void testSearchLimit() throws Exception { String indexUid = "SearchLimit"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); SearchRequest searchRequest = new SearchRequest("a").setLimit(2); - SearchResult searchResult = index.search(searchRequest); - - assertEquals(2, searchResult.getHits().size()); - assertEquals(30, searchResult.getNbHits()); + SearchResponse search = movies.search(searchRequest); + assertEquals(2, search.getHits().size()); + assertEquals(30, search.getNbHits()); } /** * Test search attributesToRetrieve */ @Test - public void testRawSearchAttributesToRetrieve() throws Exception { + public void testSearchAttributesToRetrieve() throws Exception { String indexUid = "SearchAttributesToRetrieve"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); SearchRequest searchRequest = new SearchRequest("a") - .setAttributesToRetrieve(new String[]{"id", "title"}); - - Results res_gson = jsonGson.decode( - index.rawSearch(searchRequest), - Results.class - ); - - assertEquals(20, res_gson.hits.length); - assertThat(res_gson.hits[0].getId(), instanceOf(String.class)); - assertThat(res_gson.hits[0].getTitle(), instanceOf(String.class)); - assertNull(res_gson.hits[0].getPoster()); - assertNull(res_gson.hits[0].getOverview()); - assertNull(res_gson.hits[0].getRelease_date()); - assertNull(res_gson.hits[0].getLanguage()); - assertNull(res_gson.hits[0].getGenres()); - + .setAttributesToRetrieve(Stream.of("id", "title").collect(Collectors.toList())); + SearchResponse search = movies.search(searchRequest); + assertEquals(20, search.getHits().size()); + assertThat(search.getHits().get(0).getId(), instanceOf(String.class)); + assertThat(search.getHits().get(0).getTitle(), instanceOf(String.class)); + assertNull(search.getHits().get(0).getPoster()); + assertNull(search.getHits().get(0).getOverview()); + assertNull(search.getHits().get(0).getRelease_date()); + assertNull(search.getHits().get(0).getLanguage()); + assertNull(search.getHits().get(0).getGenres()); } /** @@ -164,24 +139,20 @@ public void testRawSearchAttributesToRetrieve() throws Exception { @Test public void testSearchCrop() throws Exception { String indexUid = "SearchCrop"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); SearchRequest searchRequest = new SearchRequest("and") - .setAttributesToCrop(new String[]{"overview"}) + .setAttributesToCrop(Collections.singletonList("overview")) .setCropLength(5); - - SearchResult searchResult = index.search(searchRequest); - - assertEquals(20, searchResult.getHits().size()); + SearchResponse search = movies.search(searchRequest); + assertEquals(20, search.getHits().size()); + assertEquals("aunt and uncle", search.getHits().get(0).getFormatted().getOverview()); } /** @@ -190,83 +161,64 @@ public void testSearchCrop() throws Exception { @Test public void testSearchHighlight() throws Exception { String indexUid = "SearchHighlight"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); SearchRequest searchRequest = new SearchRequest("and") - .setAttributesToHighlight(new String[]{"overview"}); - - SearchResult searchResult = index.search(searchRequest); - - assertEquals(20, searchResult.getHits().size()); + .setAttributesToHighlight(Collections.singletonList("overview")); + SearchResponse search = movies.search(searchRequest); + assertEquals(20, search.getHits().size()); + assertTrue(search.getHits().get(0).getFormatted().getOverview().contains("")); + assertTrue(search.getHits().get(0).getFormatted().getOverview().contains("")); } /** * Test search filters */ @Test - public void testRawSearchFilters() throws Exception { + public void testSearchFilters() throws Exception { String indexUid = "SearchFilters"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); SearchRequest searchRequest = new SearchRequest("and") .setFilters("title = \"The Dark Knight\""); - - Results res_gson = jsonGson.decode( - index.rawSearch(searchRequest), - Results.class - ); - - assertEquals(1, res_gson.hits.length); - assertEquals("155", res_gson.hits[0].getId()); - assertEquals("The Dark Knight", res_gson.hits[0].getTitle()); + SearchResponse search = movies.search(searchRequest); + assertEquals(1, search.getHits().size()); + assertEquals("155", search.getHits().get(0).getId()); + assertEquals("The Dark Knight", search.getHits().get(0).getTitle()); } /** * Test search filters complex */ @Test - public void testRawSearchFiltersComplex() throws Exception { + public void testSearchFiltersComplex() throws Exception { String indexUid = "SearchFiltersComplex"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); SearchRequest searchRequest = new SearchRequest("and") .setFilters("title = \"The Dark Knight\" OR id = 290859"); - - Results res_gson = jsonGson.decode( - index.rawSearch(searchRequest), - Results.class - ); - - assertEquals(2, res_gson.hits.length); - assertEquals("155", res_gson.hits[0].getId()); - assertEquals("290859", res_gson.hits[1].getId()); + SearchResponse search = movies.search(searchRequest); + assertEquals(2, search.getHits().size()); + assertEquals("155", search.getHits().get(0).getId()); + assertEquals("290859", search.getHits().get(1).getId()); } /** @@ -275,41 +227,45 @@ public void testRawSearchFiltersComplex() throws Exception { @Test public void testSearchMatches() throws Exception { String indexUid = "SearchMatches"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); - SearchRequest searchRequest = new SearchRequest("and").setMatches(true); - SearchResult searchResult = index.search(searchRequest); - - assertEquals(20, searchResult.getHits().size()); + SearchRequest searchRequest = new SearchRequest("and") + .setMatches(true); + SearchResponse search = movies.search(searchRequest); + + assertEquals(20, search.getHits().size()); + assertEquals(52, search.getHits().get(0).getMatchesInfo().get("overview").get(0).start); + assertEquals(3, search.getHits().get(0).getMatchesInfo().get("overview").get(0).length); + assertEquals(214, search.getHits().get(0).getMatchesInfo().get("overview").get(1).start); + assertEquals(3, search.getHits().get(0).getMatchesInfo().get("overview").get(1).length); + assertEquals(375, search.getHits().get(0).getMatchesInfo().get("overview").get(2).start); + assertEquals(3, search.getHits().get(0).getMatchesInfo().get("overview").get(2).length); } + /** * Test place holder search */ @Test public void testPlaceHolder() throws Exception { String indexUid = "placeHolder"; - Index index = client.index(indexUid); + Index index = client.index().createIndex(indexUid); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - SearchResult result = index.search(""); - - assertEquals(20, result.getLimit()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); + + SearchResponse emptySearch = movies.search(""); + SearchResponse nullSearch = movies.search(new SearchRequest(null)); + assertThat(emptySearch.getHits().size(), equalTo(nullSearch.getHits().size())); + assertEquals(20, nullSearch.getHits().size()); } /** @@ -318,18 +274,15 @@ public void testPlaceHolder() throws Exception { @Test public void testPlaceHolderWithLimit() throws Exception { String indexUid = "BasicSearch"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - - index.waitForPendingUpdate(updateInfo.getUpdateId()); - SearchResult searchResult = index.search(new SearchRequest(null).setLimit(10)); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); - assertEquals(10, searchResult.getHits().size()); + SearchResponse search = movies.search(new SearchRequest(null).setLimit(10)); + assertEquals(10, search.getHits().size()); } } diff --git a/src/test/java/com/meilisearch/integration/SettingsTest.java b/src/test/java/com/meilisearch/integration/SettingsTest.java index 86816859..6469d896 100644 --- a/src/test/java/com/meilisearch/integration/SettingsTest.java +++ b/src/test/java/com/meilisearch/integration/SettingsTest.java @@ -2,7 +2,10 @@ import com.meilisearch.integration.classes.AbstractIT; import com.meilisearch.integration.classes.TestData; -import com.meilisearch.sdk.*; +import com.meilisearch.sdk.api.documents.DocumentHandler; +import com.meilisearch.sdk.api.documents.Update; +import com.meilisearch.sdk.api.index.Index; +import com.meilisearch.sdk.api.index.Settings; import com.meilisearch.sdk.json.GsonJsonHandler; import com.meilisearch.sdk.utils.Movie; import org.junit.jupiter.api.AfterAll; @@ -13,6 +16,7 @@ import java.util.HashMap; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; @Tag("integration") public class SettingsTest extends AbstractIT { @@ -37,17 +41,14 @@ static void cleanMeiliSearch() { @Test public void testGetSettings() throws Exception { String indexUid = "getSettings"; - Index index = client.index(indexUid); - GsonJsonHandler jsonGson = new GsonJsonHandler(); + Index index = client.index().getOrCreateIndex(indexUid, ""); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); - Settings settings = index.getSettings(); + Settings settings = client.index().getSettings(indexUid); assertEquals(6, settings.getRankingRules().length); } @@ -58,18 +59,15 @@ public void testGetSettings() throws Exception { @Test public void testUpdateSettingsRankingRules() throws Exception { String indexUid = "updateSettingsRankingRules"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); - - Settings settings = index.getSettings(); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); + Settings settings = new Settings(); settings.setRankingRules(new String[]{ "typo", "words", @@ -79,8 +77,10 @@ public void testUpdateSettingsRankingRules() throws Exception { "exactness", "desc(release_date)", "desc(rank)"}); - index.waitForPendingUpdate(index.updateSettings(settings).getUpdateId()); - Settings newSettings = index.getSettings(); + + update = client.index().updateSettings(indexUid, settings); + movies.waitForPendingUpdate(update.getUpdateId()); + Settings newSettings = client.index().getSettings(indexUid); assertEquals(8, newSettings.getRankingRules().length); } @@ -90,26 +90,24 @@ public void testUpdateSettingsRankingRules() throws Exception { @Test public void testUpdateSettingsSynonyms() throws Exception { String indexUid = "updateSettingsSynonyms"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); - Settings settings = index.getSettings(); + Settings settings = new Settings(); - HashMap synonyms = new HashMap(); - synonyms.put("wolverine", new String[] {"xmen", "logan"}); - synonyms.put("logan", new String[] {"wolverine"}); + HashMap synonyms = new HashMap<>(); + synonyms.put("wolverine", new String[]{"xmen", "logan"}); + synonyms.put("logan", new String[]{"wolverine"}); settings.setSynonyms(synonyms); - index.waitForPendingUpdate(index.updateSettings(settings).getUpdateId()); - - Settings newSettings = index.getSettings(); + update = client.index().updateSettings(indexUid, settings); + movies.waitForPendingUpdate(update.getUpdateId()); + Settings newSettings = client.index().getSettings(indexUid); assertEquals(2, newSettings.getSynonyms().size()); } @@ -120,30 +118,30 @@ public void testUpdateSettingsSynonyms() throws Exception { @Test public void testResetSettings() throws Exception { String indexUid = "testResetSettings"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - UpdateStatus updateInfo = jsonGson.decode( - index.addDocuments(testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); - Settings initialSettings = index.getSettings(); + Settings initialSettings = new Settings(); Settings settingsWithSynonyms = new Settings(); HashMap synonyms = new HashMap(); - synonyms.put("wolverine", new String[] {"xmen", "logan"}); - synonyms.put("logan", new String[] {"wolverine"}); + synonyms.put("wolverine", new String[]{"xmen", "logan"}); + synonyms.put("logan", new String[]{"wolverine"}); settingsWithSynonyms.setSynonyms(synonyms); + update = client.index().updateSettings(indexUid, settingsWithSynonyms); + movies.waitForPendingUpdate(update.getUpdateId()); - index.waitForPendingUpdate(index.updateSettings(settingsWithSynonyms).getUpdateId()); - settingsWithSynonyms = index.getSettings(); + settingsWithSynonyms = client.index().getSettings(indexUid); assertEquals(2, settingsWithSynonyms.getSynonyms().size()); - index.waitForPendingUpdate(index.resetSettings().getUpdateId()); - Settings settingsAfterReset = index.getSettings(); + Update resetUpdate = client.index().resetSettings(indexUid); + movies.waitForPendingUpdate(resetUpdate.getUpdateId()); + Settings settingsAfterReset = client.index().getSettings(indexUid); assertEquals(initialSettings.getSynonyms().size(), settingsAfterReset.getSynonyms().size()); } } diff --git a/src/test/java/com/meilisearch/integration/UpdatesTest.java b/src/test/java/com/meilisearch/integration/UpdatesTest.java index 3b135b04..14434a5b 100644 --- a/src/test/java/com/meilisearch/integration/UpdatesTest.java +++ b/src/test/java/com/meilisearch/integration/UpdatesTest.java @@ -2,14 +2,17 @@ import com.meilisearch.integration.classes.AbstractIT; import com.meilisearch.integration.classes.TestData; -import com.meilisearch.sdk.Index; -import com.meilisearch.sdk.UpdateStatus; +import com.meilisearch.sdk.api.documents.DocumentHandler; +import com.meilisearch.sdk.api.documents.Update; +import com.meilisearch.sdk.api.index.Index; import com.meilisearch.sdk.utils.Movie; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import java.util.List; + import static org.junit.jupiter.api.Assertions.*; @Tag("integration") @@ -35,17 +38,16 @@ static void cleanMeiliSearch() { @Test public void testGetUpdate() throws Exception { String indexUid = "GetUpdate"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(this.testData.getRaw()), - UpdateStatus.class - ); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); - UpdateStatus updateStatus = index.getUpdate(updateInfo.getUpdateId()); - assertNotNull(updateStatus.getStatus()); - assertNotEquals("", updateStatus.getStatus()); - assertTrue(updateStatus.getUpdateId() >= 0); + update = movies.getUpdate(update.getUpdateId()); + assertNotNull(update.getStatus()); + assertNotEquals("", update.getStatus()); + assertTrue(update.getUpdateId() >= 0); } /** @@ -54,19 +56,18 @@ public void testGetUpdate() throws Exception { @Test public void testGetUpdates() throws Exception { String indexUid = "GetUpdates"; - Index index = client.index(indexUid); - - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(this.testData.getRaw()), - UpdateStatus.class - ); - updateInfo = this.gson.fromJson( - index.addDocuments(this.testData.getRaw()), - UpdateStatus.class - ); - - UpdateStatus[] updateStatus = index.getUpdates(); - assertTrue(updateStatus.length == 2); + Index index = client.index().getOrCreateIndex(indexUid, ""); + + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); + update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); + update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); + + List updates = movies.getUpdates(); + assertEquals(4, updates.size()); } /** @@ -75,19 +76,16 @@ public void testGetUpdates() throws Exception { @Test public void testWaitForPendingUpdate() throws Exception { String indexUid = "WaitForPendingUpdate"; - Index index = client.index(indexUid); - - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(this.testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + Index index = client.index().getOrCreateIndex(indexUid, ""); - UpdateStatus updateStatus = index.getUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); + movies.waitForPendingUpdate(update.getUpdateId()); + update = movies.getUpdate(update.getUpdateId()); - assertEquals("processed", updateStatus.getStatus()); + assertEquals("processed", update.getStatus()); - client.deleteIndex(index.getUid()); + client.index().deleteIndex(index.getUid()); } /** @@ -96,21 +94,16 @@ public void testWaitForPendingUpdate() throws Exception { @Test public void testWaitForPendingUpdateTimoutInMs() throws Exception { String indexUid = "WaitForPendingUpdateTimoutInMs"; - Index index = client.index(indexUid); + Index index = client.index().getOrCreateIndex(indexUid, ""); - UpdateStatus updateInfo = this.gson.fromJson( - index.addDocuments(this.testData.getRaw()), - UpdateStatus.class - ); - index.waitForPendingUpdate(updateInfo.getUpdateId()); + DocumentHandler movies = client.documents("movies", Movie.class); + Update update = movies.addDocuments(testData.getData()); assertThrows( Exception.class, - () -> index.waitForPendingUpdate(updateInfo.getUpdateId(), 0, 50) + () -> movies.waitForPendingUpdate(update.getUpdateId(), 0, 50) ); - client.deleteIndex(index.getUid()); + client.index().deleteIndex(index.getUid()); } - - } diff --git a/src/test/java/com/meilisearch/integration/classes/AbstractIT.java b/src/test/java/com/meilisearch/integration/classes/AbstractIT.java index d37e1bcb..13edaeb2 100644 --- a/src/test/java/com/meilisearch/integration/classes/AbstractIT.java +++ b/src/test/java/com/meilisearch/integration/classes/AbstractIT.java @@ -4,12 +4,16 @@ import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.meilisearch.sdk.Client; +import com.meilisearch.sdk.ClientBuilder; import com.meilisearch.sdk.Config; -import com.meilisearch.sdk.Index; +import com.meilisearch.sdk.api.index.Index; +import com.meilisearch.sdk.http.ApacheHttpClient; +import com.meilisearch.sdk.json.GsonJsonHandler; import com.meilisearch.sdk.utils.Movie; import java.io.*; import java.net.URL; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -32,8 +36,13 @@ public AbstractIT() { } public void setUp() { - if (client == null) - client = new Client(new Config("http://localhost:7700", "masterKey")); + if (client == null) { + Map> modelMapping = Collections.singletonMap("movies", Movie.class); + Config config = new Config("http://localhost:7700", "masterKey", modelMapping); + ApacheHttpClient httpClient = new ApacheHttpClient(config); + GsonJsonHandler handler = new GsonJsonHandler(); + client = ClientBuilder.withConfig(config).withHttpClient(httpClient).withJsonHandler(handler).build(); + } } @@ -56,10 +65,15 @@ public void loadResource(String fileName) throws IOException { static public void deleteAllIndexes() { try { - Client ms = new Client(new Config("http://localhost:7700", "masterKey")); - Index[] indexes = ms.getIndexList(); + Map> modelMapping = Collections.singletonMap("movies", Movie.class); + Config config = new Config("http://localhost:7700", "masterKey", modelMapping); + ApacheHttpClient httpClient = new ApacheHttpClient(config); + GsonJsonHandler handler = new GsonJsonHandler(); + Client ms = ClientBuilder.withConfig(config).withHttpClient(httpClient).withJsonHandler(handler).build(); + + Index[] indexes = ms.index().getAllIndexes(); for (Index index : indexes) { - ms.deleteIndex(index.getUid()); + ms.index().deleteIndex(index.getUid()); } } catch (Exception e) { e.printStackTrace(); diff --git a/src/test/java/com/meilisearch/sdk/GenericServiceTemplateTest.java b/src/test/java/com/meilisearch/sdk/GenericServiceTemplateTest.java index 47fc8f2f..011828b4 100644 --- a/src/test/java/com/meilisearch/sdk/GenericServiceTemplateTest.java +++ b/src/test/java/com/meilisearch/sdk/GenericServiceTemplateTest.java @@ -20,8 +20,9 @@ class GenericServiceTemplateTest { private final AbstractHttpClient client = mock(AbstractHttpClient.class); + private final Config config = new Config("http://localhost:7700","masterKey"); private final JsonHandler handler = mock(JsonHandler.class); - private final GenericServiceTemplate classToTest = new GenericServiceTemplate(client, handler, new BasicRequestFactory(handler)); + private final GenericServiceTemplate classToTest = new GenericServiceTemplate(client, handler, new BasicRequestFactory(handler, config)); @Test void getClient() { diff --git a/src/test/java/com/meilisearch/sdk/api/documents/DocumentHandlerTest.java b/src/test/java/com/meilisearch/sdk/api/documents/DocumentHandlerTest.java index 62ffeca4..30791626 100644 --- a/src/test/java/com/meilisearch/sdk/api/documents/DocumentHandlerTest.java +++ b/src/test/java/com/meilisearch/sdk/api/documents/DocumentHandlerTest.java @@ -1,6 +1,7 @@ package com.meilisearch.sdk.api.documents; import com.fasterxml.jackson.databind.ObjectMapper; +import com.meilisearch.sdk.Config; import com.meilisearch.sdk.GenericServiceTemplate; import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; import com.meilisearch.sdk.http.AbstractHttpClient; @@ -23,7 +24,8 @@ class DocumentHandlerTest { private final AbstractHttpClient client = mock(AbstractHttpClient.class); private final JsonHandler jsonHandler = new JacksonJsonHandler(new ObjectMapper()); - private final RequestFactory requestFactory = new BasicRequestFactory(jsonHandler); + private final Config config = new Config("http://localhost:7700","masterKey"); + private final RequestFactory requestFactory = new BasicRequestFactory(jsonHandler, config); private final GenericServiceTemplate serviceTemplate = new GenericServiceTemplate(client, jsonHandler, requestFactory); private final DocumentHandler classToTest = new DocumentHandler(serviceTemplate, requestFactory, "movies", Movie.class); diff --git a/src/test/java/com/meilisearch/sdk/api/index/IndexHandlerTest.java b/src/test/java/com/meilisearch/sdk/api/index/IndexHandlerTest.java index 39535dd4..d41fa8df 100644 --- a/src/test/java/com/meilisearch/sdk/api/index/IndexHandlerTest.java +++ b/src/test/java/com/meilisearch/sdk/api/index/IndexHandlerTest.java @@ -1,8 +1,11 @@ package com.meilisearch.sdk.api.index; import com.fasterxml.jackson.databind.ObjectMapper; +import com.meilisearch.sdk.Config; import com.meilisearch.sdk.GenericServiceTemplate; import com.meilisearch.sdk.api.documents.Update; +import com.meilisearch.sdk.api.instance.IndexStats; +import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; import com.meilisearch.sdk.http.AbstractHttpClient; import com.meilisearch.sdk.http.factory.BasicRequestFactory; import com.meilisearch.sdk.http.factory.RequestFactory; @@ -18,18 +21,18 @@ import java.util.Deque; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.*; class IndexHandlerTest { private final AbstractHttpClient client = mock(AbstractHttpClient.class); private final JsonHandler jsonHandler = new JacksonJsonHandler(new ObjectMapper()); private final SettingsHandler settingsService = mock(SettingsHandler.class); - private final RequestFactory requestFactory = new BasicRequestFactory(jsonHandler); + private final Config config = new Config("http://localhost:7700","masterKey"); + private final RequestFactory requestFactory = new BasicRequestFactory(jsonHandler, config); private final GenericServiceTemplate serviceTemplate = new GenericServiceTemplate(client, jsonHandler, requestFactory); private final IndexHandler classToTest = new IndexHandler(serviceTemplate, requestFactory, settingsService); @@ -104,4 +107,19 @@ void settings() { assertThat(classToTest.resetSettings("test"), is(equalTo(dummyUpdate))); assertThat(classToTest.updateSettings("test", dummySettings), is(equalTo(dummyUpdate))); } + + + @Test + void singleStats() throws Exception { + when(client.get(any(HttpRequest.class))) + .thenAnswer(invocation -> new BasicHttpResponse(null, 200, "{\"numberOfDocuments\": 19654,\"isIndexing\": false,\"fieldsDistribution\": {\"poster\": 19654,\"release_date\": 19654,\"title\": 19654,\"id\": 19654,\"overview\": 19654}}")) + .thenThrow(MeiliSearchRuntimeException.class); + IndexStats stats = classToTest.getStats("index"); + assertThat(stats.getNumberOfDocuments(), is(19654)); + assertThat(stats.getIsIndexing(), is(false)); + assertThat(stats.getFieldsDistribution().keySet(), hasItems("overview", "id", "title", "release_date", "poster")); + assertThat(stats.getFieldsDistribution().get("overview"), is(19654)); + assertThat(stats.getFieldsDistribution().get("id"), is(19654)); + assertThat(stats.getFieldsDistribution().get("title"), is(19654)); + } } diff --git a/src/test/java/com/meilisearch/sdk/api/instance/InstanceHandlerTest.java b/src/test/java/com/meilisearch/sdk/api/instance/InstanceHandlerTest.java index 107069a3..b011a28c 100644 --- a/src/test/java/com/meilisearch/sdk/api/instance/InstanceHandlerTest.java +++ b/src/test/java/com/meilisearch/sdk/api/instance/InstanceHandlerTest.java @@ -1,5 +1,6 @@ package com.meilisearch.sdk.api.instance; +import com.meilisearch.sdk.Config; import com.meilisearch.sdk.GenericServiceTemplate; import com.meilisearch.sdk.exceptions.MeiliSearchRuntimeException; import com.meilisearch.sdk.http.AbstractHttpClient; @@ -23,7 +24,8 @@ class InstanceHandlerTest { private final AbstractHttpClient client = mock(AbstractHttpClient.class); private final JsonHandler handler = new JacksonJsonHandler(); - private final RequestFactory requestFactory = new BasicRequestFactory(handler); + private final Config config = new Config("http://localhost:7700","masterKey"); + private final RequestFactory requestFactory = new BasicRequestFactory(handler, config); private final GenericServiceTemplate serviceTemplate = new GenericServiceTemplate(client, handler, requestFactory); InstanceHandler classToTest = new InstanceHandler(serviceTemplate, requestFactory); @@ -74,24 +76,10 @@ void fullStats() throws Exception { assertThat(stats.getIndexes().keySet(), hasItems("movies", "rangemovies")); IndexStats movies = stats.getIndexes().get("movies"); assertThat(movies.getNumberOfDocuments(), is(19654)); - assertThat(movies.isIndexing(), is(false)); + assertThat(movies.getIsIndexing(), is(false)); assertThat(movies.getFieldsDistribution().keySet(), hasItems("overview", "id", "title")); assertThat(movies.getFieldsDistribution().get("overview"), is(19654)); assertThat(movies.getFieldsDistribution().get("id"), is(19654)); assertThat(movies.getFieldsDistribution().get("title"), is(19654)); } - - @Test - void singleStats() throws Exception { - when(client.get(any(HttpRequest.class))) - .thenAnswer(invocation -> new BasicHttpResponse(null, 200, "{\"numberOfDocuments\": 19654,\"isIndexing\": false,\"fieldsDistribution\": {\"poster\": 19654,\"release_date\": 19654,\"title\": 19654,\"id\": 19654,\"overview\": 19654}}")) - .thenThrow(MeiliSearchRuntimeException.class); - IndexStats stats = classToTest.getStats("index"); - assertThat(stats.getNumberOfDocuments(), is(19654)); - assertThat(stats.isIndexing(), is(false)); - assertThat(stats.getFieldsDistribution().keySet(), hasItems("overview", "id", "title", "release_date", "poster")); - assertThat(stats.getFieldsDistribution().get("overview"), is(19654)); - assertThat(stats.getFieldsDistribution().get("id"), is(19654)); - assertThat(stats.getFieldsDistribution().get("title"), is(19654)); - } } diff --git a/src/test/java/com/meilisearch/sdk/api/keys/KeysHandlerTest.java b/src/test/java/com/meilisearch/sdk/api/keys/KeysHandlerTest.java index 1607af71..735a96b4 100644 --- a/src/test/java/com/meilisearch/sdk/api/keys/KeysHandlerTest.java +++ b/src/test/java/com/meilisearch/sdk/api/keys/KeysHandlerTest.java @@ -1,6 +1,7 @@ package com.meilisearch.sdk.api.keys; import com.fasterxml.jackson.databind.ObjectMapper; +import com.meilisearch.sdk.Config; import com.meilisearch.sdk.GenericServiceTemplate; import com.meilisearch.sdk.http.AbstractHttpClient; import com.meilisearch.sdk.http.factory.BasicRequestFactory; @@ -21,7 +22,8 @@ class KeysHandlerTest { private final AbstractHttpClient client = mock(AbstractHttpClient.class); private final JsonHandler processor = new JacksonJsonHandler(new ObjectMapper()); - private final RequestFactory requestFactory = new BasicRequestFactory(processor); + private final Config config = new Config("http://localhost:7700","masterKey"); + private final RequestFactory requestFactory = new BasicRequestFactory(processor, config); private final GenericServiceTemplate serviceTemplate = new GenericServiceTemplate(client, processor, requestFactory); private final KeysHandler classToTest = new KeysHandler(serviceTemplate, requestFactory); diff --git a/src/test/java/com/meilisearch/sdk/http/factory/BasicRequestFactoryTest.java b/src/test/java/com/meilisearch/sdk/http/factory/BasicRequestFactoryTest.java index c7efc4ee..cee0153f 100644 --- a/src/test/java/com/meilisearch/sdk/http/factory/BasicRequestFactoryTest.java +++ b/src/test/java/com/meilisearch/sdk/http/factory/BasicRequestFactoryTest.java @@ -1,5 +1,6 @@ package com.meilisearch.sdk.http.factory; +import com.meilisearch.sdk.Config; import com.meilisearch.sdk.http.request.HttpMethod; import com.meilisearch.sdk.http.request.HttpRequest; import com.meilisearch.sdk.json.GsonJsonHandler; @@ -13,7 +14,7 @@ class BasicRequestFactoryTest { - private final RequestFactory factory = new BasicRequestFactory(new GsonJsonHandler()); + private final RequestFactory factory = new BasicRequestFactory(new GsonJsonHandler(),new Config("")); @Test void basicUseCase() { diff --git a/src/test/resources/movies.json b/src/test/resources/movies.json index 6371856f..4e08b5cc 100644 --- a/src/test/resources/movies.json +++ b/src/test/resources/movies.json @@ -28,7 +28,7 @@ "id":454626, "title":"Sonic the Hedgehog", "poster":"https://image.tmdb.org/t/p/original/aQvJ5WPzZgYVDrxLX4R6cLJCEaQ.jpg", - "overview":"Based on the global blockbuster videogame franchise from Sega, Sonic the Hedgehog tells the story of the world\u2019s speediest hedgehog as he embraces his new home on Earth. In this live-action adventure comedy, Sonic and his new best friend team up to defend the planet from the evil genius Dr. Robotnik and his plans for world domination.", + "overview":"Based on the global blockbuster videogame franchise from Sega, Sonic the Hedgehog tells the story of the world's speediest hedgehog as he embraces his new home on Earth. In this live-action adventure comedy, Sonic and his new best friend team up to defend the planet from the evil genius Dr. Robotnik and his plans for world domination.", "release_date":"2020-02-12", "language":"en", "genres":[ @@ -42,7 +42,7 @@ "id":338762, "title":"Bloodshot", "poster":"https://image.tmdb.org/t/p/original/8WUVHemHFH2ZIP6NWkwlHWsyrEL.jpg", - "overview":"After he and his wife are murdered, marine Ray Garrison is resurrected by a team of scientists. Enhanced with nanotechnology, he becomes a superhuman, biotech killing machine\u2014'Bloodshot'. As Ray first trains with fellow super-soldiers, he cannot recall anything from his former life. But when his memories flood back and he remembers the man that killed both him and his wife, he breaks out of the facility to get revenge, only to discover that there's more to the conspiracy than he thought.", + "overview":"After he and his wife are murdered, marine Ray Garrison is resurrected by a team of scientists. Enhanced with nanotechnology, he becomes a superhuman, biotech killing machine - 'Bloodshot'. As Ray first trains with fellow super-soldiers, he cannot recall anything from his former life. But when his memories flood back and he remembers the man that killed both him and his wife, he breaks out of the facility to get revenge, only to discover that there's more to the conspiracy than he thought.", "release_date":"2020-03-05", "language":"en", "genres":[ @@ -67,7 +67,7 @@ "id":514847, "title":"The Hunt", "poster":"https://image.tmdb.org/t/p/original/wxPhn4ef1EAo5njxwBkAEVrlJJG.jpg", - "overview":"Twelve strangers wake up in a clearing. They don't know where they are\u2014or how they got there. In the shadow of a dark internet conspiracy theory, ruthless elitists gather at a remote location to hunt humans for sport. But their master plan is about to be derailed when one of the hunted turns the tables on her pursuers.", + "overview":"Twelve strangers wake up in a clearing. They don't know where they are - or how they got there. In the shadow of a dark internet conspiracy theory, ruthless elitists gather at a remote location to hunt humans for sport. But their master plan is about to be derailed when one of the hunted turns the tables on her pursuers.", "release_date":"2020-03-11", "language":"en", "genres":[ @@ -150,7 +150,7 @@ "id":385103, "title":"Scoob!", "poster":"https://image.tmdb.org/t/p/original/jHo2M1OiH9Re33jYtUQdfzPeUkx.jpg", - "overview":"In Scooby-Doo\u2019s greatest adventure yet, see the never-before told story of how lifelong friends Scooby and Shaggy first met and how they joined forces with young detectives Fred, Velma, and Daphne to form the famous Mystery Inc. Now, with hundreds of cases solved, Scooby and the gang face their biggest, toughest mystery ever: an evil plot to unleash the ghost dog Cerberus upon the world. As they race to stop this global \u201cdogpocalypse,\u201d the gang discovers that Scooby has a secret legacy and an epic destiny greater than anyone ever imagined.", + "overview":"In Scooby-Doo's greatest adventure yet, see the never-before told story of how lifelong friends Scooby and Shaggy first met and how they joined forces with young detectives Fred, Velma, and Daphne to form the famous Mystery Inc. Now, with hundreds of cases solved, Scooby and the gang face their biggest, toughest mystery ever: an evil plot to unleash the ghost dog Cerberus upon the world. As they race to stop this global 'dogpocalypse, ' the gang discovers that Scooby has a secret legacy and an epic destiny greater than anyone ever imagined.", "release_date":"2020-05-15", "language":"en", "genres":[ @@ -204,7 +204,7 @@ "id":522627, "title":"The Gentlemen", "poster":"https://image.tmdb.org/t/p/original/jtrhTYB7xSrJxR1vusu99nvnZ1g.jpg", - "overview":"American expat Mickey Pearson has built a highly profitable marijuana empire in London. When word gets out that he\u2019s looking to cash out of the business forever it triggers plots, schemes, bribery and blackmail in an attempt to steal his domain out from under him.", + "overview":"American expat Mickey Pearson has built a highly profitable marijuana empire in London. When word gets out that he's looking to cash out of the business forever it triggers plots, schemes, bribery and blackmail in an attempt to steal his domain out from under him.", "release_date":"2019-12-03", "language":"en", "genres":[ @@ -323,7 +323,7 @@ "id":545609, "title":"Extraction", "poster":"https://image.tmdb.org/t/p/original/wlfDxbGEsW58vGhFljKkcR5IxDj.jpg", - "overview":"Tyler Rake, a fearless mercenary who offers his services on the black market, embarks on a dangerous mission when he is hired to rescue the kidnapped son of a Mumbai crime lord\u2026", + "overview":"Tyler Rake, a fearless mercenary who offers his services on the black market, embarks on a dangerous mission when he is hired to rescue the kidnapped son of a Mumbai crime lord ...", "release_date":"2020-04-24", "language":"en", "genres":[