diff --git a/.code-samples.meilisearch.yaml b/.code-samples.meilisearch.yaml index 7fcab977..837a867a 100644 --- a/.code-samples.meilisearch.yaml +++ b/.code-samples.meilisearch.yaml @@ -3,12 +3,11 @@ # the documentation on build # You can read more on https://github.com/meilisearch/documentation/tree/master/.vuepress/code-samples --- -getting_started_typo_tolerance: |- - get_one_index_1: |- client.getIndex("movies"); list_all_indexes_1: |- - client.getIndexes(); + IndexesQuery query = new IndexesQuery().setLimit(3); + client.getIndexes(query); create_an_index_1: |- client.createIndex("movies", "id"); update_an_index_1: |- @@ -16,9 +15,11 @@ update_an_index_1: |- delete_an_index_1: |- client.deleteIndex("movies"); get_one_document_1: |- - client.index("movies").getDocument("25684"); + DocumentQuery query = new DocumentQuery().setFields(new String[] {"id", "title", "poster", "release_date"}); + client.index("movies").getDocument("25684", query); get_documents_1: |- - client.index("movies").getDocuments(); + DocumentsQuery query = new DocumentsQuery().setLimit(2); + client.index("movies").getDocuments(query); add_or_replace_documents_1: |- client.index("movies").addDocuments("[{" + "\"id\": 287947," @@ -49,18 +50,35 @@ delete_documents_1: |- })); search_post_1: |- client.index("movies").search("American ninja"); -get_task_by_index_1: |- - client.index("movies").getTask(1); get_all_tasks_1: |- client.getTasks(); get_task_1: |- client.getTask(1); -get_all_tasks_by_index_1: |- +get_all_tasks_filtering_1: |- client.index("movies").getTasks(); +get_all_tasks_filtering_2: |- + TasksQuery query = new TasksQuery() + .setStatus(new String[] {"succeeded", "failed"}) + .setType(new String[] {documentAdditionOrUpdate}); + + client.index("movies").getTasks(query); +get_all_tasks_paginating_1: |- + TasksQuery query = new TasksQuery() + .setLimit(2) + .setFrom(10); + + client.index("movies").getTasks(query); +get_all_tasks_paginating_2: |- + TasksQuery query = new TasksQuery() + .setLimit(2) + .setFrom(8); + + client.index("movies").getTasks(query); get_one_key_1: |- - client.getKey("d0552b41536279a0ad88bd595327b96f01176a60c2243e906c52ac02375f9bc4"); + client.getKey("6062abda-a5aa-4414-ac91-ecd7944c0f8d"); get_all_keys_1: |- - client.getKeys(); + KeysQuery query = new KeysQuery().setLimit(3); + client.getKeys(query); create_a_key_1: |- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date dateParsed = format.parse("2042-04-02T00:42:42Z"); @@ -74,20 +92,24 @@ create_a_key_1: |- client.createKey(keyInfo); update_a_key_1: |- - //Not yet implemented + KeyUpdate keyChanges = new KeyUpdate(); + keyChanges.setName("Products/Reviews API key"); + keyChanges.setDescription("Manage documents: Products/Reviews API key"); + + client.updateKey("6062abda-a5aa-4414-ac91-ecd7944c0f8d", keyChanges); delete_a_key_1: |- - client.deleteKey("d0552b41536279a0ad88bd595327b96f01176a60c2243e906c52ac02375f9bc4") + client.deleteKey("6062abda-a5aa-4414-ac91-ecd7944c0f8d") get_settings_1: |- client.index("movies").getSettings(); update_settings_1: |- Settings settings = new Settings(); settings.setRankingRules( new String[] { - "typo", "words", - "sort", + "typo", "proximity", "attribute", + "sort", "exactness", "release_date:desc", "rank:desc" @@ -117,15 +139,28 @@ update_settings_1: |- "title", "release_date" }); + HashMap synonyms = new HashMap(); synonyms.put("wolverine", new String[] {"xmen", "logan"}); synonyms.put("logan", new String[] {"wolverine"}); settings.setSynonyms(synonyms); + + HashMap minWordSizeTypos = + new HashMap() { + { + put("oneTypo", 8); + put("twoTypos", 10); + } + }; + TypoTolerance typoTolerance = new TypoTolerance(); + typoTolerance.setMinWordSizeForTypos(minWordSizeTypos); + settings.setTypoTolerance(typoTolerance); + client.index("movies").updateSettings(settings); reset_settings_1: |- client.index("movies").resetSettings(); get_synonyms_1: |- - client.index("movies").getSynonyms(); + client.index("movies").getSynonymsSettings(); update_synonyms_1: |- HashMap synonyms = new HashMap(); synonyms.put("wolverine", new String[] {"xmen", "logan"}); @@ -134,13 +169,13 @@ update_synonyms_1: |- reset_synonyms_1: |- client.index("movies").resetSynonymsSettings(); get_stop_words_1: |- - client.index("movies").getStopWords(); + client.index("movies").getStopWordsSettings(); update_stop_words_1: |- client.index("movies").updateStopWordsSettings(new String[] {"of", "the", "to"}); reset_stop_words_1: |- client.index("movies").resetStopWordsSettings(); get_ranking_rules_1: |- - client.index("movies").getRankingRules(); + client.index("movies").getRankingRuleSettings(); update_ranking_rules_1: |- Settings settings = new Settings(); settings.setRankingRules(new String[] @@ -158,13 +193,13 @@ update_ranking_rules_1: |- reset_ranking_rules_1: |- client.index("movies").resetRankingRuleSettings(); get_distinct_attribute_1: |- - client.index("shoes").getDistinctAttribute(); + client.index("shoes").getDistinctAttributeSettings(); update_distinct_attribute_1: |- client.index("shoes").updateDistinctAttributeSettings("skuid"); reset_distinct_attribute_1: |- client.index("shoes").resetDistinctAttributeSettings(); get_searchable_attributes_1: |- - client.index("movies").getSearchableAttributes(); + client.index("movies").getSearchableAttributesSettings(); update_searchable_attributes_1: |- client.index("movies").updateSearchableAttributesSettings(new String[] { @@ -175,15 +210,15 @@ update_searchable_attributes_1: |- reset_searchable_attributes_1: |- client.index("movies").resetSearchableAttributesSettings(); get_filterable_attributes_1: |- - client.index("movies").getFilterableAttributes(); + client.index("movies").getFilterableAttributesSettings(); update_filterable_attributes_1: |- Settings settings = new Settings(); settings.setFilterableAttributes(new String[] {"genres", "director"}); client.index("movies").updateSettings(settings); reset_filterable_attributes_1: |- - //Not yet implemented + client.index("movies").resetFilterableAttributesSettings(); get_displayed_attributes_1: |- - client.index("movies").getDisplayedAttributes(); + client.index("movies").getDisplayedAttributesSettings(); update_displayed_attributes_1: |- client.index("movies").updateDisplayedAttributesSettings(new String[] { @@ -194,6 +229,18 @@ update_displayed_attributes_1: |- }); reset_displayed_attributes_1: |- client.index("movies").resetDisplayedAttributesSettings(); +getting_started_typo_tolerance: |- + HashMap minWordSizeTypos = + new HashMap() { + { + put("oneTypo", 4); + } + }; + + TypoTolerance typoTolerance = new TypoTolerance(); + typoTolerance.setMinWordSizeForTypos(minWordSizeTypos); + + client.index("movies").updateTypoToleranceSettings(typoTolerance); get_typo_tolerance_1: client.index("books").getTypoToleranceSettings(); update_typo_tolerance_1: |- @@ -212,6 +259,12 @@ update_typo_tolerance_1: |- client.index("books").updateTypoToleranceSettings(typoTolerance); reset_typo_tolerance_1: |- client.index("books").resetTypoToleranceSettings(); +get_pagination_settings_1: +update_pagination_settings_1: |- +reset_pagination_settings_1: |- +get_faceting_settings_1: |- +update_faceting_settings_1: |- +reset_faceting_settings_1: |- get_index_stats_1: |- client.index("movies").getStats(); get_indexes_stats_1: |- @@ -290,9 +343,6 @@ search_parameter_guide_highlight_tag_1: |- .setHighlightPreTag("") .setHighlightPostTag(""); client.index("movies").search(searchRequest); -search_parameter_guide_matches_1: |- - SearchRequest searchRequest = new SearchRequest("winter feast").setMatches(true); - SearchResult searchResult = index.search(searchRequest); settings_guide_synonyms_1: |- Settings settings = new Settings(); HashMap synonyms = new HashMap(); @@ -354,6 +404,8 @@ settings_guide_sortable_1: |- "author", }); client.index("books").updateSettings(settings); +settings_guide_faceting_1: |- +settings_guide_pagination_1: |- settings_guide_typo_tolerance_1: |- TypoTolerance typoTolerance = new TypoTolerance(); HashMap minWordSizeTypos = @@ -428,7 +480,7 @@ getting_started_add_documents_md: |- [About this SDK](https://github.com/meilisearch/meilisearch-java) getting_started_check_task_status: |- - client.index("movies").getTask(0); + client.getTask(0); getting_started_search_md: |- ```java client.index("movies").search("botman"); @@ -527,9 +579,9 @@ faceted_search_filter_1: |- new String[] {"genres = Horror", "genres = Mystery"}, new String[] {"director = \"Jordan Peele\""}}); client.index("movies").search(searchRequest); -faceted_search_facets_distribution_1: |- +faceted_search_facets_1: |- SearchRequest searchRequest = - new SearchRequest("Batman").setFacetsDistribution(new String[] {"genres"}); + new SearchRequest("Batman").setFacets(new String[] {"genres"}); client.index("movies").search(searchRequest); faceted_search_walkthrough_filter_1: |- SearchRequest searchRequest = @@ -562,8 +614,6 @@ landing_getting_started_1: |- ); post_dump_1: |- client.createDump(); -get_dump_status_1: |- - client.getDumpStatus("20201101-110357260"); phrase_search_1: |- client.index("movies").search("\"african american\" horror"); sorting_guide_update_sortable_attributes_1: |- @@ -589,13 +639,12 @@ sorting_guide_sort_parameter_2: |- SearchRequest searchRequest = new SearchRequest("butler").setSort(new String[] {"author:desc"}); client.index("books").search(searchRequest); get_sortable_attributes_1: |- - client.index("books").getSortableAttributes(); + client.index("books").getSettings().getSortableAttributes(); update_sortable_attributes_1: |- Settings settings = new Settings(); settings.setSortableAttributes(new String[] {"price", "author"}); client.index("books").updateSettings(settings); reset_sortable_attributes_1: |- - //Not yet implemented search_parameter_guide_sort_1: |- SearchRequest searchRequest = new SearchRequest("science fiction").setSort(new String[] {"price:asc"}); client.index("search_parameter_guide_sort_1").search(searchRequest); @@ -643,7 +692,8 @@ security_guide_search_key_1: |- Client client = new Client(new Config("http://localhost:7700", "apiKey")); client.index("patient_medical_records").search(); security_guide_update_key_1: |- - //Not yet implemented + Client client = new Client(new Config("http://localhost:7700", "masterKey")); + client.updateKey("74c9c733-3368-4738-bbe5-1d18a5fecb37", new KeyUpdate().setDescription("Default Search API Key")); security_guide_create_key_1: |- Client client = new Client(new Config("http://localhost:7700", "masterKey")); @@ -663,7 +713,7 @@ security_guide_list_keys_1: |- client.getKeys(); security_guide_delete_key_1: |- Client client = new Client(new Config("http://localhost:7700", "masterKey")); - client.deleteKey("d0552b41536279a0ad88bd595327b96f01176a60c2243e906c52ac02375f9bc4"); + client.deleteKey("c5cd97d-5a4b-4226-a868-2d0eb6d197ab"); authorization_header_1: |- Client client = new Client(new Config("http://localhost:7700", "masterKey")); client.getKeys(); @@ -679,7 +729,7 @@ tenant_token_guide_generate_sdk_1: |- options.setApiKey("B5KdX2MY2jV6EXfUs6scSfmC..."); options.setExpiresAt(expiresAt); - String token = client.generateTenantToken(searchRules, options); + String token = client.generateTenantToken("85c3c2f9-bdd6-41f1-abd8-11fcf80e0f76", searchRules, options); tenant_token_guide_search_sdk_1: |- Client frontEndClient = new Client(new Config("http://localhost:7700", token)); frontEndClient.index("patient_medical_records").search("blood test"); diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a1395ae0..6b59e0e9 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -26,8 +26,8 @@ jobs: cache: gradle - name: Grant execute permission for gradlew run: chmod +x gradlew - - name: Meilisearch (v0.27.2 version) setup with Docker - run: docker run -d -p 7700:7700 getmeili/meilisearch:v0.27.2 meilisearch --no-analytics --master-key='masterKey' + - name: Meilisearch (v0.28.1 version) setup with Docker + run: docker run -d -p 7700:7700 getmeili/meilisearch:v0.28.1 meilisearch --no-analytics --master-key='masterKey' - name: Build and run unit and integration tests run: ./gradlew build integrationTest - name: Archive test report diff --git a/README.md b/README.md index ac923a1c..b851ddd3 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ class TestMeilisearch { Index index = client.index("movies"); // If the index 'movies' does not exist, Meilisearch creates it when you first add the documents. - index.addDocuments(documents); // => { "uid": 0 } + index.addDocuments(documents); // => { "taskUid": 0 } } } ``` @@ -140,7 +140,7 @@ System.out.println(results); - Output: ``` -SearchResult(hits=[{id=1.0, title=Carol, genres:[Romance, Drama]}], offset=0, limit=20, nbHits=1, exhaustiveNbHits=false, facetsDistribution=null, exhaustiveFacetsCount=false, processingTimeMs=3, query=carlo) +SearchResult(hits=[{id=1.0, title=Carol, genres:[Romance, Drama]}], offset=0, limit=20, estimatedTotalHits=1, facetDistribution=null, processingTimeMs=3, query=carlo) ``` #### Custom Search @@ -155,7 +155,7 @@ import com.meilisearch.sdk.SearchRequest; SearchResult results = index.search( new SearchRequest("of") - .setMatches(true) + .setShowMatchesPosition(true) .setAttributesToHighlight(new String[]{"title"}) ); System.out.println(results.getHits()); @@ -173,10 +173,10 @@ System.out.println(results.getHits()); "title":"Life of Pi", "genres":["Adventure","Drama"] }, - "_matchesInfo":{ + "_matchesPosition":{ "title":[{ - "start":5, - "length":2 + "start":5.0, + "length":2.0 }] } }] @@ -217,7 +217,7 @@ index.search( ], "offset": 0, "limit": 20, - "nbHits": 1, + "estimatedTotalHits": 1, "processingTimeMs": 0, "query": "wonder" } @@ -265,7 +265,7 @@ Client client = new Client(config); ## 🤖 Compatibility with Meilisearch -This package only guarantees compatibility with the [version v0.27.0 of Meilisearch](https://github.com/meilisearch/meilisearch/releases/tag/v0.27.0). +This package only guarantees compatibility with the [version v0.28.0 of Meilisearch](https://github.com/meilisearch/meilisearch/releases/tag/v0.28.0). ## 💡 Learn more diff --git a/src/main/java/com/meilisearch/sdk/Client.java b/src/main/java/com/meilisearch/sdk/Client.java index 59ddd758..1ca76f31 100644 --- a/src/main/java/com/meilisearch/sdk/Client.java +++ b/src/main/java/com/meilisearch/sdk/Client.java @@ -7,13 +7,20 @@ import com.auth0.jwt.algorithms.Algorithm; import com.meilisearch.sdk.exceptions.MeilisearchException; import com.meilisearch.sdk.json.JsonHandler; +import com.meilisearch.sdk.model.IndexesQuery; import com.meilisearch.sdk.model.Key; -import com.meilisearch.sdk.model.Result; +import com.meilisearch.sdk.model.KeyUpdate; +import com.meilisearch.sdk.model.KeysQuery; +import com.meilisearch.sdk.model.Results; import com.meilisearch.sdk.model.Stats; import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; +import com.meilisearch.sdk.model.TasksQuery; +import com.meilisearch.sdk.model.TasksResults; import java.util.Date; import java.util.Map; import java.util.TimeZone; +import java.util.UUID; /** Meilisearch client */ public class Client { @@ -43,10 +50,10 @@ public Client(Config config) { * https://docs.meilisearch.com/reference/api/indexes.html#create-an-index * * @param uid Unique identifier for the index to create - * @return Meilisearch API response as Task + * @return Meilisearch API response as TaskInfo * @throws MeilisearchException if an error occurs */ - public Task createIndex(String uid) throws MeilisearchException { + public TaskInfo createIndex(String uid) throws MeilisearchException { return this.createIndex(uid, null); } @@ -56,37 +63,50 @@ public Task createIndex(String uid) throws MeilisearchException { * * @param uid Unique identifier for the index to create * @param primaryKey The primary key of the documents in that index - * @return Meilisearch API response as Task + * @return Meilisearch API response as TaskInfo * @throws MeilisearchException if an error occurs */ - public Task createIndex(String uid, String primaryKey) throws MeilisearchException { - return this.indexesHandler.create(uid, primaryKey); + public TaskInfo createIndex(String uid, String primaryKey) throws MeilisearchException { + return this.indexesHandler.createIndex(uid, primaryKey); } /** - * Gets all indexes in the current Meilisearch instance - * https://docs.meilisearch.com/reference/api/indexes.html#list-all-indexes + * Gets indexes https://docs.meilisearch.com/reference/api/indexes.html#list-all-indexes * - * @return Array of indexes in the Meilisearch client + * @return Results containing a list of indexes from the Meilisearch API * @throws MeilisearchException if an error occurs */ - public Index[] getIndexes() throws MeilisearchException { - Index[] indexes = jsonHandler.decode(getRawIndexes(), Index[].class); - for (Index index : indexes) { + public Results getIndexes() throws MeilisearchException { + Results indexes = this.indexesHandler.getIndexes(); + for (Index index : indexes.getResults()) { index.setConfig(this.config); } return indexes; } /** - * Gets all indexes in the current Meilisearch instance - * https://docs.meilisearch.com/reference/api/indexes.html#list-all-indexes + * Gets indexes https://docs.meilisearch.com/reference/api/indexes.html#list-all-indexes * - * @return Meilisearch API response as String + * @param params query parameters accepted by the get indexes route + * @return Results containing a list of indexes from the Meilisearch API + * @throws MeilisearchException if an error occurs + */ + public Results getIndexes(IndexesQuery params) throws MeilisearchException { + Results indexes = this.indexesHandler.getIndexes(params); + for (Index index : indexes.getResults()) { + index.setConfig(this.config); + } + return indexes; + } + + /** + * Gets all indexes https://docs.meilisearch.com/reference/api/indexes.html#list-all-indexes + * + * @return List of indexes from the Meilisearch API as String * @throws MeilisearchException if an error occurs */ public String getRawIndexes() throws MeilisearchException { - return this.indexesHandler.getAll(); + return this.indexesHandler.getRawIndexes(); } /** @@ -95,7 +115,7 @@ public String getRawIndexes() throws MeilisearchException { * methods in the Index class. * * @param uid Unique identifier of the index - * @return Index instance + * @return Meilisearch API response as Index instance * @throws MeilisearchException if an error occurs */ public Index index(String uid) throws MeilisearchException { @@ -110,37 +130,25 @@ public Index index(String uid) throws MeilisearchException { * https://docs.meilisearch.com/reference/api/indexes.html#get-one-index * * @param uid Unique identifier of the index to get - * @return Meilisearch API response + * @return Meilisearch API response as Index instance * @throws MeilisearchException if an error occurs */ public Index getIndex(String uid) throws MeilisearchException { - Index index = jsonHandler.decode(getRawIndex(uid), Index.class); + Index index = this.indexesHandler.getIndex(uid); index.setConfig(this.config); return index; } /** - * Gets single index by its unique identifier - * https://docs.meilisearch.com/reference/api/indexes.html#get-one-index - * - * @param uid Unique identifier of the index to get - * @return Meilisearch API response as String - * @throws MeilisearchException if an error occurs - */ - public String getRawIndex(String uid) throws MeilisearchException { - return this.indexesHandler.get(uid); - } - - /** - * Updates the primary key of an index in the Meilisearch instance + * Updates the primary key of an index * 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 as Task + * @return Meilisearch API response as TaskInfo * @throws MeilisearchException if an error occurs */ - public Task updateIndex(String uid, String primaryKey) throws MeilisearchException { + public TaskInfo updateIndex(String uid, String primaryKey) throws MeilisearchException { return this.indexesHandler.updatePrimaryKey(uid, primaryKey); } @@ -149,33 +157,23 @@ public Task updateIndex(String uid, String primaryKey) throws MeilisearchExcepti * https://docs.meilisearch.com/reference/api/indexes.html#delete-one-index * * @param uid Unique identifier of the index to delete - * @return Meilisearch API response as Task + * @return Meilisearch API response as TaskInfo * @throws MeilisearchException if an error occurs */ - public Task deleteIndex(String uid) throws MeilisearchException { - return this.indexesHandler.delete(uid); + public TaskInfo deleteIndex(String uid) throws MeilisearchException { + return this.indexesHandler.deleteIndex(uid); } - // TODO createDump will return a Task in v0.28 - // /** - // * Triggers the creation of a Meilisearch dump. - // * https://docs.meilisearch.com/reference/api/dump.html#create-a-dump - // * - // * @return Dump instance - // * @throws MeilisearchException if an error occurs - // */ - // public Dump createDump() throws MeilisearchException { - // return this.dumpHandler.createDump(); - // } - // /** - // * Creates a dump https://docs.meilisearch.com/reference/api/dump.html#create-a-dump - // * - // * @return Dump object with Meilisearch API response - // * @throws MeilisearchException if an error occurs - // */ - // public Dump createDump() throws MeilisearchException { - // return this.meiliSearchHttpRequest.post("/dumps", "", Dump.class); - // } + /** + * Triggers the creation of a Meilisearch dump. + * https://docs.meilisearch.com/reference/api/dump.html#create-a-dump + * + * @return Meilisearch API response as TaskInfo + * @throws MeilisearchException if an error occurs + */ + public TaskInfo createDump() throws MeilisearchException { + return config.httpClient.post("/dumps", "", TaskInfo.class); + } /** * Gets the status and availability of a Meilisearch instance @@ -227,7 +225,7 @@ public String getVersion() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/tasks.html#get-one-task * * @param uid Identifier of the requested Task - * @return Task Instance + * @return Meilisearch API response as Task Instance * @throws MeilisearchException if an error occurs */ public Task getTask(int uid) throws MeilisearchException { @@ -237,13 +235,24 @@ public Task getTask(int uid) throws MeilisearchException { /** * Retrieves list of tasks https://docs.meilisearch.com/reference/api/tasks.html#get-tasks * - * @return List of tasks in the Meilisearch client + * @return TasksResults containing a list of tasks from the Meilisearch API * @throws MeilisearchException if an error occurs */ - public Result getTasks() throws MeilisearchException { + public TasksResults getTasks() throws MeilisearchException { return this.tasksHandler.getTasks(); } + /** + * Retrieves list of tasks https://docs.meilisearch.com/reference/api/tasks.html#get-tasks + * + * @param param accept by the tasks route + * @return TasksResults containing a list of tasks from the Meilisearch API + * @throws MeilisearchException if an error occurs + */ + public TasksResults getTasks(TasksQuery param) throws MeilisearchException { + return this.tasksHandler.getTasks(param); + } + /** * Waits for a task to be processed * @@ -259,7 +268,7 @@ public void waitForTask(int uid) throws MeilisearchException { * https://docs.meilisearch.com/reference/api/keys.html#get-one-key * * @param uid Identifier of the requested Key - * @return Key Instance + * @return Meilisearch API response as Key Instance * @throws MeilisearchException if an error occurs */ public Key getKey(String uid) throws MeilisearchException { @@ -269,18 +278,29 @@ public Key getKey(String uid) throws MeilisearchException { /** * Retrieves list of keys https://docs.meilisearch.com/reference/api/keys.html#get-all-keys * - * @return List of keys in the Meilisearch client + * @return Results containing a list of Key from the Meilisearch API * @throws MeilisearchException if an error occurs */ - public Result getKeys() throws MeilisearchException { + public Results getKeys() throws MeilisearchException { return this.keysHandler.getKeys(); } + /** + * Get list of all API keys https://docs.meilisearch.com/reference/api/keys.html#get-all-keys + * + * @param params query parameters accepted by the get keys route + * @return Results containing a list of Key from the Meilisearch API + * @throws MeilisearchException if an error occurs + */ + public Results getKeys(KeysQuery params) throws MeilisearchException { + return this.keysHandler.getKeys(params); + } + /** * Creates a key https://docs.meilisearch.com/reference/api/keys.html#create-a-key * * @param options Key containing the options of the key - * @return Key Instance + * @return Meilisearch API response as Key Instance * @throws MeilisearchException if an error occurs */ public Key createKey(Key options) throws MeilisearchException { @@ -292,10 +312,10 @@ public Key createKey(Key options) throws MeilisearchException { * * @param key String containing the key * @param options String containing the options to update - * @return Key Instance - * @throws Exception if client request causes an error + * @return Meilisearch API response as Key Instance + * @throws MeilisearchException if an error occurs */ - public Key updateKey(String key, Key options) throws Exception { + public Key updateKey(String key, KeyUpdate options) throws MeilisearchException { return this.keysHandler.updateKey(key, options); } @@ -309,14 +329,16 @@ public void deleteKey(String key) throws MeilisearchException { this.keysHandler.deleteKey(key); } - public String generateTenantToken(Map searchRules) throws MeilisearchException { - return this.generateTenantToken(searchRules, new TenantTokenOptions()); + public String generateTenantToken(String apiKeyUid, Map searchRules) + throws MeilisearchException { + return this.generateTenantToken(apiKeyUid, searchRules, new TenantTokenOptions()); } /** * Generate a tenant token * https://docs.meilisearch.com/learn/security/tenant_tokens.html#multitenancy-and-tenant-tokens * + * @param apiKeyUid Uid of a signing API key. * @param searchRules A Map of string, object which contains the rules to be enforced at search * time for all or specific accessible indexes for the signing API Key. * @param options A TenantTokenOptions, the following fileds are accepted: - apiKey: String @@ -326,7 +348,8 @@ public String generateTenantToken(Map searchRules) throws Meilis * @return String containing the tenant token * @throws MeilisearchException if an error occurs */ - public String generateTenantToken(Map searchRules, TenantTokenOptions options) + public String generateTenantToken( + String apiKeyUid, Map searchRules, TenantTokenOptions options) throws MeilisearchException { // Validate all fields Date now = new Date(); @@ -349,6 +372,10 @@ public String generateTenantToken(Map searchRules, TenantTokenOp throw new MeilisearchException( "The searchRules field is mandatory and should be defined."); } + if (apiKeyUid == "" || apiKeyUid == null || !isValidUUID(apiKeyUid)) { + throw new MeilisearchException( + "The uid used for the token generation must exist and comply to uuid4 format"); + } // Encrypt the key Algorithm algorithm = Algorithm.HMAC256(secret); @@ -357,10 +384,19 @@ public String generateTenantToken(Map searchRules, TenantTokenOp String jwtToken = JWT.create() .withClaim("searchRules", searchRules) - .withClaim("apiKeyPrefix", secret.substring(0, 8)) + .withClaim("apiKeyUid", apiKeyUid) .withExpiresAt(options.getExpiresAt()) .sign(algorithm); return jwtToken; } + + private Boolean isValidUUID(String apiKeyUid) { + try { + UUID uuid = UUID.fromString(apiKeyUid); + } catch (IllegalArgumentException exception) { + return false; + } + return true; + } } diff --git a/src/main/java/com/meilisearch/sdk/Documents.java b/src/main/java/com/meilisearch/sdk/Documents.java index 56f6009d..7179729c 100644 --- a/src/main/java/com/meilisearch/sdk/Documents.java +++ b/src/main/java/com/meilisearch/sdk/Documents.java @@ -1,9 +1,11 @@ package com.meilisearch.sdk; -import static java.util.Collections.singletonList; - import com.meilisearch.sdk.exceptions.MeilisearchException; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.http.URLBuilder; +import com.meilisearch.sdk.model.DocumentQuery; +import com.meilisearch.sdk.model.DocumentsQuery; +import com.meilisearch.sdk.model.Results; +import com.meilisearch.sdk.model.TaskInfo; import java.util.List; /** @@ -14,90 +16,125 @@ class Documents { private final HttpClient httpClient; + /** + * Creates and sets up an instance of Documents to simplify Meilisearch API calls to manage + * documents + * + * @param config Meilisearch configuration + */ protected Documents(Config config) { - httpClient = config.httpClient; + this.httpClient = config.httpClient; } /** - * Retrieves the document at the specified index uid with the specified identifier + * Retrieves the document from the specified index uid with the specified identifier * + * @param Type of the document returned * @param uid Partial index identifier for the requested documents * @param identifier ID of the document - * @return String containing the requested document + * @param targetClass Class of the document returned + * @return Object containing the requested document + * @throws MeilisearchException if the client request causes an error + */ + T getDocument(String uid, String identifier, Class targetClass) + throws MeilisearchException { + return httpClient.get(documentPath(uid, identifier).getURL(), targetClass); + } + + /** + * Retrieves the document from the specified index uid with the specified identifier + * + * @param uid Partial index identifier for the requested documents + * @param identifier ID of the document + * @param param accepted by the get document route + * @param targetClass Class of the document returned + * @return Object containing the requested document * @throws MeilisearchException if client request causes an error */ - String getDocument(String uid, String identifier) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/documents/" + identifier; - return httpClient.get(urlPath, String.class); + T getDocument(String uid, String identifier, DocumentQuery param, Class targetClass) + throws MeilisearchException { + return httpClient.get( + documentPath(uid, identifier).addQuery(param.toQuery()).getURL(), targetClass); } /** - * Retrieves the document at the specified index + * Retrieves the document from the specified index uid with the specified identifier * * @param uid Partial index identifier for the requested documents + * @param identifier ID of the document * @return String containing the requested document - * @throws MeilisearchException if the client request causes an error + * @throws MeilisearchException if client request causes an error */ - String getDocuments(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/documents"; - return httpClient.get(urlPath, String.class); + String getRawDocument(String uid, String identifier) throws MeilisearchException { + return httpClient.get(documentPath(uid, identifier).getURL(), String.class); } /** - * Retrieves the document at the specified index + * Retrieves the document from the specified index uid with the specified identifier * * @param uid Partial index identifier for the requested documents - * @param limit Limit on the requested documents to be returned + * @param identifier ID of the document + * @param param accept by the documents route * @return String containing the requested document - * @throws MeilisearchException if the client request causes an error + * @throws MeilisearchException if client request causes an error */ - String getDocuments(String uid, int limit) throws MeilisearchException { - String urlQuery = "/indexes/" + uid + "/documents?limit=" + limit; - return httpClient.get(urlQuery, String.class); + String getRawDocument(String uid, String identifier, DocumentQuery param) + throws MeilisearchException { + return httpClient.get( + documentPath(uid, identifier).addQuery(param.toQuery()).getURL(), String.class); } /** - * Retrieves the document at the specified index + * Retrieves the document from the specified index * + * @param Type of documents returned * @param uid Partial index identifier for the requested documents - * @param limit Limit on the requested documents to be returned - * @param offset Specify the offset of the first hit to return - * @return String containing the requested document + * @param targetClass Class of documents returned + * @return Results containing a list of Object containing the requested document * @throws MeilisearchException if the client request causes an error */ - String getDocuments(String uid, int limit, int offset) throws MeilisearchException { - String urlQuery = "/indexes/" + uid + "/documents?limit=" + limit + "&offset=" + offset; - return httpClient.get(urlQuery, String.class); + Results getDocuments(String uid, Class targetClass) throws MeilisearchException { + return httpClient.get(documentPath(uid).getURL(), Results.class, targetClass); } /** - * Retrieves the document at the specified index + * Retrieves the document from the specified index * + * @param Type of documents returned * @param uid Partial index identifier for the requested documents - * @param limit Limit on the requested documents to be returned - * @param offset Specify the offset of the first hit to return - * @param attributesToRetrieve Document attributes to show - * @return String containing the requested document + * @param param accepted by the get documents route + * @param targetClass Class of documents returned + * @return Results containing a list of Object containing the requested document * @throws MeilisearchException if the client request causes an error */ - String getDocuments(String uid, int limit, int offset, List attributesToRetrieve) + Results getDocuments(String uid, DocumentsQuery param, Class targetClass) throws MeilisearchException { - if (attributesToRetrieve == null || attributesToRetrieve.size() == 0) { - attributesToRetrieve = singletonList("*"); - } + return httpClient.get( + documentPath(uid).addQuery(param.toQuery()).getURL(), Results.class, targetClass); + } - String attributesToRetrieveCommaSeparated = String.join(",", attributesToRetrieve); - String urlQuery = - "/indexes/" - + uid - + "/documents?limit=" - + limit - + "&offset=" - + offset - + "&attributesToRetrieve=" - + attributesToRetrieveCommaSeparated; + /** + * Retrieves the document as a string from the specified index + * + * @param uid Partial index identifier for the requested documents + * @return Meilisearch API response + * @throws MeilisearchException if an error occurs + */ + String getRawDocuments(String uid) throws MeilisearchException { + return httpClient.get(documentPath(uid).getURL(), String.class); + } - return httpClient.get(urlQuery, String.class); + /** + * Retrieves the document as String from the specified index + * + * @param uid Partial index identifier for the requested documents + * @param param accepted by the documents route + * @return Meilisearch API response + * @throws MeilisearchException if an error occurs + */ + String getRawDocuments(String uid, DocumentsQuery param) throws MeilisearchException { + return httpClient.get( + documentPath(uid).addQuery(param.toQuery()).getURL(), String.class); } /** @@ -106,15 +143,16 @@ String getDocuments(String uid, int limit, int offset, List attributesTo * @param uid Partial index identifier for the document * @param document String containing the document to add * @param primaryKey PrimaryKey of the document - * @return Meilisearch's Task API response + * @return Meilisearch's TaskInfo API response * @throws MeilisearchException if the client request causes an error */ - Task addDocuments(String uid, String document, String primaryKey) throws MeilisearchException { - String urlQuery = "/indexes/" + uid + "/documents"; + TaskInfo addDocuments(String uid, String document, String primaryKey) + throws MeilisearchException { + URLBuilder urlb = documentPath(uid); if (primaryKey != null) { - urlQuery += "?primaryKey=" + primaryKey; + urlb.addParameter("primaryKey", primaryKey); } - return httpClient.post(urlQuery, document, Task.class); + return httpClient.post(urlb.getURL(), document, TaskInfo.class); } /** @@ -123,29 +161,28 @@ Task addDocuments(String uid, String document, String primaryKey) throws Meilise * @param uid Partial index identifier for the document * @param document String containing the document to replace the existing document * @param primaryKey PrimaryKey of the document - * @return Meilisearch's Task API response + * @return Meilisearch's TaskInfo API response * @throws MeilisearchException if the client request causes an error */ - Task updateDocuments(String uid, String document, String primaryKey) + TaskInfo updateDocuments(String uid, String document, String primaryKey) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/documents"; + URLBuilder urlb = documentPath(uid); if (primaryKey != null) { - urlPath += "?primaryKey=" + primaryKey; + urlb.addParameter("primaryKey", primaryKey); } - return httpClient.put(urlPath, document, Task.class); + return httpClient.put(urlb.getURL(), document, TaskInfo.class); } /** - * Deletes the document at the specified index uid with the specified identifier + * Deletes the document from the specified index uid with the specified identifier * * @param uid Partial index identifier for the requested document * @param identifier ID of the document - * @return Meilisearch's Task API response + * @return Meilisearch's TaskInfo API response * @throws MeilisearchException if the client request causes an error */ - Task deleteDocument(String uid, String identifier) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/documents/" + identifier; - return httpClient.delete(urlPath, Task.class); + TaskInfo deleteDocument(String uid, String identifier) throws MeilisearchException { + return httpClient.delete(documentPath(uid, identifier).getURL(), TaskInfo.class); } /** @@ -153,23 +190,36 @@ Task deleteDocument(String uid, String identifier) throws MeilisearchException { * * @param uid Partial index identifier for the requested documents * @param identifiers ID of documents to delete - * @return Meilisearch's Task API response + * @return Meilisearch's TaskInfo API response * @throws MeilisearchException if the client request causes an error */ - Task deleteDocuments(String uid, List identifiers) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/documents/" + "delete-batch"; - return httpClient.post(urlPath, identifiers, Task.class); + TaskInfo deleteDocuments(String uid, List identifiers) throws MeilisearchException { + URLBuilder urlb = documentPath(uid).addSubroute("delete-batch"); + return httpClient.post(urlb.getURL(), identifiers, TaskInfo.class); } /** * Deletes all documents at the specified index uid * * @param uid Partial index identifier for the requested documents - * @return Meilisearch's Task API response + * @return Meilisearch's TaskInfo API response * @throws MeilisearchException if the client request causes an error */ - Task deleteAllDocuments(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/documents"; - return httpClient.delete(urlPath, Task.class); + TaskInfo deleteAllDocuments(String uid) throws MeilisearchException { + return httpClient.delete(documentPath(uid).getURL(), TaskInfo.class); + } + + /** Creates an URLBuilder for the constant route documents. */ + private URLBuilder documentPath(String uid) { + return new URLBuilder().addSubroute("indexes").addSubroute(uid).addSubroute("documents"); + } + + /** Creates an URLBuilder for the constant route documents */ + private URLBuilder documentPath(String uid, String identifier) { + return new URLBuilder() + .addSubroute("indexes") + .addSubroute(uid) + .addSubroute("documents") + .addSubroute(identifier); } } diff --git a/src/main/java/com/meilisearch/sdk/Index.java b/src/main/java/com/meilisearch/sdk/Index.java index 67ccbe24..47913dc5 100644 --- a/src/main/java/com/meilisearch/sdk/Index.java +++ b/src/main/java/com/meilisearch/sdk/Index.java @@ -1,11 +1,16 @@ package com.meilisearch.sdk; import com.meilisearch.sdk.exceptions.MeilisearchException; +import com.meilisearch.sdk.model.DocumentQuery; +import com.meilisearch.sdk.model.DocumentsQuery; import com.meilisearch.sdk.model.IndexStats; -import com.meilisearch.sdk.model.Result; +import com.meilisearch.sdk.model.Results; import com.meilisearch.sdk.model.SearchResult; import com.meilisearch.sdk.model.Settings; import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; +import com.meilisearch.sdk.model.TasksQuery; +import com.meilisearch.sdk.model.TasksResults; import com.meilisearch.sdk.model.TypoTolerance; import java.io.Serializable; import java.util.ArrayList; @@ -47,63 +52,107 @@ void setConfig(Config config) { * Gets a documents with the specified uid Refer * https://docs.meilisearch.com/reference/api/documents.html#get-one-document * + * @param Type of documents returned * @param identifier Identifier of the document to get - * @return Meilisearch API response + * @param targetClass Class of the document returned + * @return Object containing the requested document * @throws MeilisearchException if an error occurs */ - public String getDocument(String identifier) throws MeilisearchException { - return this.documents.getDocument(this.uid, identifier); + public T getDocument(String identifier, Class targetClass) throws MeilisearchException { + return this.documents.getDocument(this.uid, identifier, targetClass); } /** - * Gets documenta at the specified index Refer + * Gets a documents with the specified uid Refer + * https://docs.meilisearch.com/reference/api/documents.html#get-one-document + * + * @param Type of documents returned + * @param identifier Identifier of the document to get + * @param param accepted by the get document route + * @param targetClass Class of documents returned + * @return Object containing the requested document + * @throws MeilisearchException if an error occurs + */ + public T getDocument(String identifier, DocumentQuery param, Class targetClass) + throws MeilisearchException { + return this.documents.getDocument(this.uid, identifier, param, targetClass); + } + + /** + * Gets a documents with the specified uid Refer + * https://docs.meilisearch.com/reference/api/documents.html#get-one-document + * + * @param identifier Identifier of the document to get + * @return String containing the requested document + * @throws MeilisearchException if an error occurs + */ + public String getRawDocument(String identifier) throws MeilisearchException { + return this.documents.getRawDocument(this.uid, identifier); + } + + /** + * Gets a document with the specified uid and parameters + * https://docs.meilisearch.com/reference/api/documents.html#get-one-document + * + * @param identifier Identifier of the document to get + * @param param accept by the documents route + * @return String containing the requested document + * @throws MeilisearchException if an error occurs + */ + public String getRawDocument(String identifier, DocumentQuery param) + throws MeilisearchException { + return this.documents.getRawDocument(this.uid, identifier, param); + } + + /** + * Gets documents at the specified index Refer * https://docs.meilisearch.com/reference/api/documents.html#get-documents * - * @return Meilisearch API response + * @param Type of documents returned + * @param targetClass Class of documents returned + * @return Results containing a list of Object containing the requested document * @throws MeilisearchException if an error occurs */ - public String getDocuments() throws MeilisearchException { - return this.documents.getDocuments(this.uid); + public Results getDocuments(Class targetClass) throws MeilisearchException { + return this.documents.getDocuments(this.uid, targetClass); } /** - * Gets documents at the specified index and limit the number of documents returned Refer + * Gets documents at the specified index Refer * https://docs.meilisearch.com/reference/api/documents.html#get-documents * - * @param limits Maximum amount of documents to return - * @return Meilisearch API response + * @param Type of documents returned + * @param param accept by the documents route + * @param targetClass Class of documents returned + * @return Results containing a list of Object containing the requested document * @throws MeilisearchException if an error occurs */ - public String getDocuments(int limits) throws MeilisearchException { - return this.documents.getDocuments(this.uid, limits); + public Results getDocuments(DocumentsQuery param, Class targetClass) + throws MeilisearchException { + return this.documents.getDocuments(this.uid, param, targetClass); } /** - * Gets documents at the specified index and limit the number of documents returned Refer + * Gets documents as String at the specified index Refer * https://docs.meilisearch.com/reference/api/documents.html#get-documents * - * @param limits Maximum amount of documents to return - * @param offset Number of documents to skip - * @return Meilisearch API response + * @return String containing a list of documents * @throws MeilisearchException if an error occurs */ - public String getDocuments(int limits, int offset) throws MeilisearchException { - return this.documents.getDocuments(this.uid, limits, offset); + public String getRawDocuments() throws MeilisearchException { + return this.documents.getRawDocuments(this.uid); } /** - * Gets documents at the specified index and limit the number of documents returned Refer + * Gets documents as String at the specified index Refer * https://docs.meilisearch.com/reference/api/documents.html#get-documents * - * @param limits Maximum amount of documents to return - * @param offset Number of documents to skip - * @param attributesToRetrieve Document attributes to show - * @return Meilisearch API response + * @param param accept by the documents route + * @return String containing a list of documents * @throws MeilisearchException if an error occurs */ - public String getDocuments(int limits, int offset, List attributesToRetrieve) - throws MeilisearchException { - return this.documents.getDocuments(this.uid, limits, offset, attributesToRetrieve); + public String getRawDocuments(DocumentsQuery param) throws MeilisearchException { + return this.documents.getRawDocuments(this.uid, param); } /** @@ -111,10 +160,10 @@ public String getDocuments(int limits, int offset, List attributesToRetr * https://docs.meilisearch.com/reference/api/documents.html#add-or-replace-documents * * @param document Document to add in JSON string format - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task addDocuments(String document) throws MeilisearchException { + public TaskInfo addDocuments(String document) throws MeilisearchException { return this.documents.addDocuments(this.uid, document, null); } @@ -124,10 +173,10 @@ public Task addDocuments(String document) throws MeilisearchException { * * @param document Document to add in JSON string format * @param primaryKey PrimaryKey of the document to add - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task addDocuments(String document, String primaryKey) throws MeilisearchException { + public TaskInfo addDocuments(String document, String primaryKey) throws MeilisearchException { return this.documents.addDocuments(this.uid, document, primaryKey); } @@ -138,15 +187,15 @@ public Task addDocuments(String document, String primaryKey) throws MeilisearchE * @param batchSize size of the batch of documents * @param document Document to add in JSON string format * @param primaryKey PrimaryKey of the document to add - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task[] addDocumentsInBatches(String document, Integer batchSize, String primaryKey) + public TaskInfo[] addDocumentsInBatches(String document, Integer batchSize, String primaryKey) throws MeilisearchException { JSONArray jsonDocumentsArray = new JSONArray(document); JSONArray jsonSubArray = new JSONArray(); - List arrayResponses = new ArrayList(); + List arrayResponses = new ArrayList(); batchSize = jsonDocumentsArray.length() < batchSize ? jsonDocumentsArray.length() : batchSize; @@ -158,7 +207,7 @@ public Task[] addDocumentsInBatches(String document, Integer batchSize, String p arrayResponses.add( this.documents.addDocuments(this.uid, jsonSubArray.toString(), primaryKey)); } - return arrayResponses.toArray(new Task[arrayResponses.size()]); + return arrayResponses.toArray(new TaskInfo[arrayResponses.size()]); } /** @@ -166,10 +215,10 @@ public Task[] addDocumentsInBatches(String document, Integer batchSize, String p * https://docs.meilisearch.com/reference/api/documents.html#add-or-replace-documents * * @param document Document to add in JSON string format - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task[] addDocumentsInBatches(String document) throws MeilisearchException { + public TaskInfo[] addDocumentsInBatches(String document) throws MeilisearchException { return this.addDocumentsInBatches(document, 1000, null); } @@ -178,10 +227,10 @@ public Task[] addDocumentsInBatches(String document) throws MeilisearchException * https://docs.meilisearch.com/reference/api/documents.html#add-or-update-documents * * @param document Document to update in JSON string format - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task updateDocuments(String document) throws MeilisearchException { + public TaskInfo updateDocuments(String document) throws MeilisearchException { return this.documents.updateDocuments(this.uid, document, null); } @@ -191,10 +240,11 @@ public Task updateDocuments(String document) throws MeilisearchException { * * @param document Document to update in JSON string format * @param primaryKey PrimaryKey of the document - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task updateDocuments(String document, String primaryKey) throws MeilisearchException { + public TaskInfo updateDocuments(String document, String primaryKey) + throws MeilisearchException { return this.documents.updateDocuments(this.uid, document, primaryKey); } @@ -205,15 +255,15 @@ public Task updateDocuments(String document, String primaryKey) throws Meilisear * @param document Document to add in JSON string format * @param batchSize size of the batch of documents * @param primaryKey PrimaryKey of the document to add - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task[] updateDocumentsInBatches(String document, Integer batchSize, String primaryKey) - throws MeilisearchException { + public TaskInfo[] updateDocumentsInBatches( + String document, Integer batchSize, String primaryKey) throws MeilisearchException { JSONArray jsonDocumentsArray = new JSONArray(document); JSONArray jsonSubArray = new JSONArray(); - List arrayResponses = new ArrayList(); + List arrayResponses = new ArrayList(); batchSize = jsonDocumentsArray.length() < batchSize ? jsonDocumentsArray.length() : batchSize; @@ -225,7 +275,7 @@ public Task[] updateDocumentsInBatches(String document, Integer batchSize, Strin arrayResponses.add( this.documents.updateDocuments(this.uid, jsonSubArray.toString(), primaryKey)); } - return arrayResponses.toArray(new Task[arrayResponses.size()]); + return arrayResponses.toArray(new TaskInfo[arrayResponses.size()]); } /** @@ -233,10 +283,10 @@ public Task[] updateDocumentsInBatches(String document, Integer batchSize, Strin * https://docs.meilisearch.com/reference/api/documents.html#add-or-update-documents * * @param document Document to add in JSON string format - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task[] updateDocumentsInBatches(String document) throws MeilisearchException { + public TaskInfo[] updateDocumentsInBatches(String document) throws MeilisearchException { return this.updateDocumentsInBatches(document, 1000, null); } @@ -245,10 +295,10 @@ public Task[] updateDocumentsInBatches(String document) throws MeilisearchExcept * https://docs.meilisearch.com/reference/api/documents.html#delete-one-document * * @param identifier Identifier of the document to delete - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task deleteDocument(String identifier) throws MeilisearchException { + public TaskInfo deleteDocument(String identifier) throws MeilisearchException { return this.documents.deleteDocument(this.uid, identifier); } @@ -257,10 +307,10 @@ public Task deleteDocument(String identifier) throws MeilisearchException { * https://docs.meilisearch.com/reference/api/documents.html#delete-documents-by-batch * * @param documentsIdentifiers list of identifiers of documents to delete - * @return Task Meilisearch API response + * @return TaskInfo Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task deleteDocuments(List documentsIdentifiers) throws MeilisearchException { + public TaskInfo deleteDocuments(List documentsIdentifiers) throws MeilisearchException { return this.documents.deleteDocuments(this.uid, documentsIdentifiers); } @@ -271,7 +321,7 @@ public Task deleteDocuments(List documentsIdentifiers) throws Meilisearc * @return List of tasks Meilisearch API response * @throws MeilisearchException if an error occurs */ - public Task deleteAllDocuments() throws MeilisearchException { + public TaskInfo deleteAllDocuments() throws MeilisearchException { return this.documents.deleteAllDocuments(this.uid); } @@ -323,10 +373,10 @@ public Settings getSettings() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/settings.html#update-settings * * @param settings the object that contains the data with the new settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateSettings(Settings settings) throws MeilisearchException { + public TaskInfo updateSettings(Settings settings) throws MeilisearchException { return this.settingsHandler.updateSettings(this.uid, settings); } @@ -334,10 +384,10 @@ public Task updateSettings(Settings settings) throws MeilisearchException { * Resets the settings of the index Refer * https://docs.meilisearch.com/reference/api/settings.html#reset-settings * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetSettings() throws MeilisearchException { + public TaskInfo resetSettings() throws MeilisearchException { return this.settingsHandler.resetSettings(this.uid); } @@ -357,10 +407,10 @@ public String[] getRankingRuleSettings() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/settings.html#update-settings * * @param rankingRules array that contain the data with the new ranking rules - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateRankingRuleSettings(String[] rankingRules) throws MeilisearchException { + public TaskInfo updateRankingRuleSettings(String[] rankingRules) throws MeilisearchException { return this.settingsHandler.updateRankingRuleSettings(this.uid, rankingRules); } @@ -368,10 +418,10 @@ public Task updateRankingRuleSettings(String[] rankingRules) throws MeilisearchE * Resets the ranking rule settings of the index Refer * https://docs.meilisearch.com/reference/api/settings.html#reset-settings * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetRankingRuleSettings() throws MeilisearchException { + public TaskInfo resetRankingRuleSettings() throws MeilisearchException { return this.settingsHandler.resetRankingRulesSettings(this.uid); } @@ -391,10 +441,11 @@ public Map getSynonymsSettings() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/synonyms.html#update-synonyms * * @param synonyms key (String) value (array) pair of synonyms - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateSynonymsSettings(Map synonyms) throws MeilisearchException { + public TaskInfo updateSynonymsSettings(Map synonyms) + throws MeilisearchException { return this.settingsHandler.updateSynonymsSettings(this.uid, synonyms); } @@ -402,10 +453,10 @@ public Task updateSynonymsSettings(Map synonyms) throws Meilis * Resets the synonyms settings of the index Refer * https://docs.meilisearch.com/reference/api/synonyms.html#reset-synonyms * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetSynonymsSettings() throws MeilisearchException { + public TaskInfo resetSynonymsSettings() throws MeilisearchException { return this.settingsHandler.resetSynonymsSettings(this.uid); } @@ -425,10 +476,10 @@ public String[] getStopWordsSettings() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/stop_words.html#update-stop-words * * @param stopWords An array of strings that contains the stop-words. - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateStopWordsSettings(String[] stopWords) throws MeilisearchException { + public TaskInfo updateStopWordsSettings(String[] stopWords) throws MeilisearchException { return this.settingsHandler.updateStopWordsSettings(this.uid, stopWords); } @@ -436,10 +487,10 @@ public Task updateStopWordsSettings(String[] stopWords) throws MeilisearchExcept * Resets the stop-words settings of the index Refer * https://docs.meilisearch.com/reference/api/stop_words.html#reset-stop-words * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetStopWordsSettings() throws MeilisearchException { + public TaskInfo resetStopWordsSettings() throws MeilisearchException { return this.settingsHandler.resetStopWordsSettings(this.uid); } @@ -459,10 +510,10 @@ public String[] getSearchableAttributesSettings() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/searchable_attributes.html#update-searchable-attributes * * @param searchableAttributes An array of strings that contains the searchable attributes. - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateSearchableAttributesSettings(String[] searchableAttributes) + public TaskInfo updateSearchableAttributesSettings(String[] searchableAttributes) throws MeilisearchException { return this.settingsHandler.updateSearchableAttributesSettings( this.uid, searchableAttributes); @@ -472,10 +523,10 @@ public Task updateSearchableAttributesSettings(String[] searchableAttributes) * Resets the searchable attributes of the index Refer * https://docs.meilisearch.com/reference/api/searchable_attributes.html#reset-searchable-attributes * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetSearchableAttributesSettings() throws MeilisearchException { + public TaskInfo resetSearchableAttributesSettings() throws MeilisearchException { return this.settingsHandler.resetSearchableAttributesSettings(this.uid); } @@ -495,10 +546,10 @@ public String[] getDisplayedAttributesSettings() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/displayed_attributes.html#update-displayed-attributes * * @param displayAttributes An array of strings that contains attributes of an index to display - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateDisplayedAttributesSettings(String[] displayAttributes) + public TaskInfo updateDisplayedAttributesSettings(String[] displayAttributes) throws MeilisearchException { return this.settingsHandler.updateDisplayedAttributesSettings(this.uid, displayAttributes); } @@ -507,10 +558,10 @@ public Task updateDisplayedAttributesSettings(String[] displayAttributes) * Resets the displayed attributes of the index Refer * https://docs.meilisearch.com/reference/api/displayed_attributes.html#reset-displayed-attributes * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetDisplayedAttributesSettings() throws MeilisearchException { + public TaskInfo resetDisplayedAttributesSettings() throws MeilisearchException { return this.settingsHandler.resetDisplayedAttributesSettings(this.uid); } @@ -532,10 +583,10 @@ public String[] getFilterableAttributesSettings() throws MeilisearchException { * * @param filterableAttributes An array of strings containing the attributes that can be used as * filters at query time. - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateFilterableAttributesSettings(String[] filterableAttributes) + public TaskInfo updateFilterableAttributesSettings(String[] filterableAttributes) throws MeilisearchException { return this.settingsHandler.updateFilterableAttributesSettings( this.uid, filterableAttributes); @@ -545,10 +596,10 @@ public Task updateFilterableAttributesSettings(String[] filterableAttributes) * Resets the filterable attributes of the index Refer * https://docs.meilisearch.com/reference/api/filterable_attributes.html#reset-filterable-attributes * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetFilterableAttributesSettings() throws MeilisearchException { + public TaskInfo resetFilterableAttributesSettings() throws MeilisearchException { return this.settingsHandler.resetFilterableAttributesSettings(this.uid); } @@ -568,10 +619,10 @@ public String getDistinctAttributeSettings() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/distinct_attribute.html#update-distinct-attribute * * @param distinctAttribute A String: the field name. - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateDistinctAttributeSettings(String distinctAttribute) + public TaskInfo updateDistinctAttributeSettings(String distinctAttribute) throws MeilisearchException { return this.settingsHandler.updateDistinctAttributeSettings(this.uid, distinctAttribute); } @@ -580,10 +631,10 @@ public Task updateDistinctAttributeSettings(String distinctAttribute) * Resets the distinct attribute field of the index Refer * https://docs.meilisearch.com/reference/api/distinct_attribute.html#reset-distinct-attribute * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetDistinctAttributeSettings() throws MeilisearchException { + public TaskInfo resetDistinctAttributeSettings() throws MeilisearchException { return this.settingsHandler.resetDistinctAttributeSettings(this.uid); } @@ -603,10 +654,10 @@ public TypoTolerance getTypoToleranceSettings() throws MeilisearchException { * https://docs.meilisearch.com/reference/api/typo_tolerance.html#update-typo-tolerance * * @param typoTolerance A TypoTolerance instance - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task updateTypoToleranceSettings(TypoTolerance typoTolerance) + public TaskInfo updateTypoToleranceSettings(TypoTolerance typoTolerance) throws MeilisearchException { return this.settingsHandler.updateTypoToleranceSettings(this.uid, typoTolerance); } @@ -615,10 +666,10 @@ public Task updateTypoToleranceSettings(TypoTolerance typoTolerance) * Resets the typo tolerance field of the index Refer * https://docs.meilisearch.com/reference/api/typo_tolerance.html#reset-typo-tolerance * - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - public Task resetTypoToleranceSettings() throws MeilisearchException { + public TaskInfo resetTypoToleranceSettings() throws MeilisearchException { return this.settingsHandler.resetTypoToleranceSettings(this.uid); } @@ -642,7 +693,7 @@ public IndexStats getStats() throws MeilisearchException { * @throws MeilisearchException if an error occurs */ public Task getTask(int taskId) throws MeilisearchException { - return this.tasksHandler.getTask(this.uid, taskId); + return this.tasksHandler.getTask(taskId); } /** @@ -652,10 +703,22 @@ public Task getTask(int taskId) throws MeilisearchException { * @return List of tasks in the Meilisearch index * @throws MeilisearchException if an error occurs */ - public Result getTasks() throws MeilisearchException { + public TasksResults getTasks() throws MeilisearchException { return this.tasksHandler.getTasks(this.uid); } + /** + * Retrieves list of tasks of the index Refer + * https://docs.meilisearch.com/reference/api/tasks.html#get-tasks + * + * @param param accept by the tasks route + * @return List of tasks in the Meilisearch index + * @throws MeilisearchException if an error occurs + */ + public TasksResults getTasks(TasksQuery param) throws MeilisearchException { + return this.tasksHandler.getTasks(this.uid, param); + } + /** * Waits for a task to be processed Refer * https://docs.meilisearch.com/reference/api/tasks.html#task-object diff --git a/src/main/java/com/meilisearch/sdk/IndexesHandler.java b/src/main/java/com/meilisearch/sdk/IndexesHandler.java index 30ec5167..d999f39d 100644 --- a/src/main/java/com/meilisearch/sdk/IndexesHandler.java +++ b/src/main/java/com/meilisearch/sdk/IndexesHandler.java @@ -1,7 +1,10 @@ package com.meilisearch.sdk; import com.meilisearch.sdk.exceptions.MeilisearchException; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.http.URLBuilder; +import com.meilisearch.sdk.model.IndexesQuery; +import com.meilisearch.sdk.model.Results; +import com.meilisearch.sdk.model.TaskInfo; import java.util.HashMap; /** @@ -10,7 +13,7 @@ *

https://docs.meilisearch.com/reference/api/indexes.html */ class IndexesHandler { - HttpClient httpClient; + private final HttpClient httpClient; /** * Creates and sets up an instance of IndexesHandler to simplify Meilisearch API calls to manage @@ -18,57 +21,78 @@ class IndexesHandler { * * @param config Meilisearch configuration */ - IndexesHandler(Config config) { + protected IndexesHandler(Config config) { this.httpClient = config.httpClient; } /** * Creates an index with a unique identifier * - * @param uid Unique identifier to create the index with - * @return Meilisearch API response + * @param uid Unique identifier of the index + * @return Meilisearch API response as TaskInfo * @throws MeilisearchException if an error occurs */ - Task create(String uid) throws MeilisearchException { - return this.create(uid, null); + TaskInfo createIndex(String uid) throws MeilisearchException { + return this.createIndex(uid, null); } /** * Creates an index with a unique identifier * - * @param uid Unique identifier to create the index with + * @param uid Unique identifier of the index * @param primaryKey Field to use as the primary key for documents in that index - * @return Meilisearch API response + * @return Meilisearch API response as TaskInfo * @throws MeilisearchException if an error occurs */ - Task create(String uid, String primaryKey) throws MeilisearchException { + TaskInfo createIndex(String uid, String primaryKey) throws MeilisearchException { HashMap index = new HashMap(); index.put("uid", uid); index.put("primaryKey", primaryKey); - return httpClient.post("/indexes", index, Task.class); + return httpClient.post(indexesPath().getURL(), index, TaskInfo.class); } /** * Gets an index from its uid * * @param uid Unique identifier of the index to get - * @return Meilisearch API response + * @return Meilisearch API response as Index instance * @throws MeilisearchException if an error occurs */ - String get(String uid) throws MeilisearchException { - String requestQuery = "/indexes/" + uid; - return httpClient.get(requestQuery, String.class); + Index getIndex(String uid) throws MeilisearchException { + return httpClient.get(indexesPath().addSubroute(uid).getURL(), Index.class); } /** - * Gets all indexes in the current Meilisearch instance + * Gets indexes in the current Meilisearch instance * - * @return Meilisearch API response + * @return Results containing a list of indexes * @throws MeilisearchException if an error occurs */ - String getAll() throws MeilisearchException { - return httpClient.get("/indexes", String.class); + Results getIndexes() throws MeilisearchException { + return httpClient.get(indexesPath().getURL(), Results.class, Index.class); + } + + /** + * Gets indexes in the current Meilisearch instance + * + * @param query parameters accepted by the indexes route + * @return Results containing a list of indexes + * @throws MeilisearchException if an error occurs + */ + Results getIndexes(IndexesQuery params) throws MeilisearchException { + return httpClient.get( + indexesPath().addQuery(params.toQuery()).getURL(), Results.class, Index.class); + } + + /** + * Gets indexes in the current Meilisearch instance + * + * @return List of indexes as String + * @throws MeilisearchException if an error occurs + */ + String getRawIndexes() throws MeilisearchException { + return httpClient.get(indexesPath().getURL(), String.class); } /** @@ -76,26 +100,29 @@ String getAll() throws MeilisearchException { * * @param uid Unique identifier of the index to update * @param primaryKey New primary key field to use for documents in that index - * @return Meilisearch API response + * @return Meilisearch API response as TaskInfo * @throws MeilisearchException if an error occurs */ - Task updatePrimaryKey(String uid, String primaryKey) throws MeilisearchException { + TaskInfo updatePrimaryKey(String uid, String primaryKey) throws MeilisearchException { HashMap index = new HashMap(); index.put("primaryKey", primaryKey); - String requestQuery = "/indexes/" + uid; - return httpClient.put(requestQuery, index, Task.class); + return httpClient.patch(indexesPath().addSubroute(uid).getURL(), index, TaskInfo.class); } /** * Deletes an index in the Meilisearch instance * * @param uid Unique identifier of the index to delete - * @return Meilisearch API response + * @return Meilisearch API response as TaskInfo * @throws MeilisearchException if an error occurs */ - Task delete(String uid) throws MeilisearchException { - String requestQuery = "/indexes/" + uid; - return httpClient.delete(requestQuery, Task.class); + TaskInfo deleteIndex(String uid) throws MeilisearchException { + return httpClient.delete(indexesPath().addSubroute(uid).getURL(), TaskInfo.class); + } + + /** Creates an URLBuilder for the constant route indexes */ + private URLBuilder indexesPath() { + return new URLBuilder("/indexes"); } } diff --git a/src/main/java/com/meilisearch/sdk/InstanceHandler.java b/src/main/java/com/meilisearch/sdk/InstanceHandler.java index 785e9240..7f55f86c 100644 --- a/src/main/java/com/meilisearch/sdk/InstanceHandler.java +++ b/src/main/java/com/meilisearch/sdk/InstanceHandler.java @@ -10,14 +10,14 @@ *

https://docs.meilisearch.com/reference/api/keys.html */ public class InstanceHandler { - HttpClient httpClient; + private final HttpClient httpClient; /** * Creates and sets up an instance of InstanceHandler * * @param config Meilisearch configuration */ - InstanceHandler(Config config) { + protected InstanceHandler(Config config) { this.httpClient = config.httpClient; } diff --git a/src/main/java/com/meilisearch/sdk/KeysHandler.java b/src/main/java/com/meilisearch/sdk/KeysHandler.java index 2537ddff..7a742c6a 100644 --- a/src/main/java/com/meilisearch/sdk/KeysHandler.java +++ b/src/main/java/com/meilisearch/sdk/KeysHandler.java @@ -1,8 +1,11 @@ package com.meilisearch.sdk; import com.meilisearch.sdk.exceptions.MeilisearchException; +import com.meilisearch.sdk.http.URLBuilder; import com.meilisearch.sdk.model.Key; -import com.meilisearch.sdk.model.Result; +import com.meilisearch.sdk.model.KeyUpdate; +import com.meilisearch.sdk.model.KeysQuery; +import com.meilisearch.sdk.model.Results; /** * Class covering the Meilisearch Key API @@ -17,7 +20,7 @@ public class KeysHandler { * * @param config Meilisearch configuration */ - KeysHandler(Config config) { + protected KeysHandler(Config config) { this.httpClient = config.httpClient; } @@ -29,20 +32,29 @@ public class KeysHandler { * @throws MeilisearchException if client request causes an error */ Key getKey(String uid) throws MeilisearchException { - String urlPath = "/keys/" + uid; - return httpClient.get(urlPath, Key.class); + return httpClient.get(keysPath().addSubroute(uid).getURL(), Key.class); } /** * Retrieves keys from the client * - * @return List of key instance + * @return Results containing a list of Key instance * @throws MeilisearchException if client request causes an error */ - Result getKeys() throws MeilisearchException { - String urlPath = "/keys"; - Result result = httpClient.get(urlPath, Result.class, Key.class); - return result; + Results getKeys() throws MeilisearchException { + return httpClient.get(keysPath().getURL(), Results.class, Key.class); + } + + /** + * Retrieves keys from the client + * + * @param params accept by the keys route + * @return Results containing a list of Key instance + * @throws MeilisearchException if client request causes an error + */ + Results getKeys(KeysQuery params) throws MeilisearchException { + return httpClient.get( + keysPath().addQuery(params.toQuery()).getURL(), Results.class, Key.class); } /** @@ -53,8 +65,7 @@ Result getKeys() throws MeilisearchException { * @throws MeilisearchException if client request causes an error */ Key createKey(Key options) throws MeilisearchException { - String urlPath = "/keys"; - return httpClient.post(urlPath, options, Key.class); + return httpClient.post(keysPath().getURL(), options, Key.class); } /** @@ -63,11 +74,10 @@ Key createKey(Key options) throws MeilisearchException { * @param key String containing the key * @param options String containing the options of the key * @return Key Instance - * @throws Exception if client request causes an error + * @throws MeilisearchException if client request causes an error */ - Key updateKey(String key, Key options) throws Exception { - String urlPath = "/keys/" + key; - return httpClient.patch(urlPath, options, Key.class); + Key updateKey(String key, KeyUpdate options) throws MeilisearchException { + return httpClient.patch(keysPath().addSubroute(key).getURL(), options, Key.class); } /** @@ -77,7 +87,11 @@ Key updateKey(String key, Key options) throws Exception { * @throws MeilisearchException if client request causes an error */ void deleteKey(String key) throws MeilisearchException { - String urlPath = "/keys/" + key; - httpClient.delete(urlPath, String.class); + httpClient.delete(keysPath().addSubroute(key).getURL(), String.class); + } + + /** Creates an URLBuilder for the constant route keys */ + private URLBuilder keysPath() { + return new URLBuilder("/keys"); } } diff --git a/src/main/java/com/meilisearch/sdk/Search.java b/src/main/java/com/meilisearch/sdk/Search.java index f7d3d5b7..3ba0d573 100644 --- a/src/main/java/com/meilisearch/sdk/Search.java +++ b/src/main/java/com/meilisearch/sdk/Search.java @@ -48,9 +48,9 @@ String rawSearch(String uid, String q) throws MeilisearchException { * @param highlightPostTag String to customize highlight tag after every highlighted query terms * @param attributesToHighlight Attributes whose values will contain highlighted matching terms * @param filter Filter queries by an attribute value - * @param matches Defines whether an object that contains information about the matches should - * be returned or not - * @param facetsDistribution Facets for which to retrieve the matching count + * @param showMatchesPosition Defines whether an object that contains information about the + * matches should be returned or not + * @param facets Facets for which to retrieve the matching count * @param sort Sort queries by an attribute value * @return search results, as raw data * @throws MeilisearchException Search Exception or Client Error @@ -68,8 +68,8 @@ String rawSearch( String highlightPostTag, String[] attributesToHighlight, String[] filter, - boolean matches, - String[] facetsDistribution, + boolean showMatchesPosition, + String[] facets, String[] sort) throws MeilisearchException { String requestQuery = "/indexes/" + uid + "/search"; @@ -86,8 +86,8 @@ String rawSearch( highlightPostTag, attributesToHighlight, filter, - matches, - facetsDistribution, + showMatchesPosition, + facets, sort); return httpClient.post(requestQuery, sr, String.class); } @@ -131,9 +131,9 @@ SearchResult search(String uid, String q) throws MeilisearchException { * @param highlightPostTag String to customize highlight tag after every highlighted query terms * @param attributesToHighlight Attributes whose values will contain highlighted matching terms * @param filter Filter queries by an attribute value - * @param matches Defines whether an object that contains information about the matches should - * be returned or not - * @param facetsDistribution Facets for which to retrieve the matching count + * @param showMatchesPosition Defines whether an object that contains information about the + * matches should be returned or not + * @param facets Facets for which to retrieve the matching count * @param sort Sort queries by an attribute value * @return search results * @throws MeilisearchException Search Exception or Client Error @@ -151,8 +151,8 @@ SearchResult search( String highlightPostTag, String[] attributesToHighlight, String[] filter, - boolean matches, - String[] facetsDistribution, + boolean showMatchesPosition, + String[] facets, String[] sort) throws MeilisearchException { return httpClient.jsonHandler.decode( @@ -169,8 +169,8 @@ SearchResult search( highlightPostTag, attributesToHighlight, filter, - matches, - facetsDistribution, + showMatchesPosition, + facets, sort), SearchResult.class); } diff --git a/src/main/java/com/meilisearch/sdk/SearchRequest.java b/src/main/java/com/meilisearch/sdk/SearchRequest.java index e251a02d..a6a0f4b2 100644 --- a/src/main/java/com/meilisearch/sdk/SearchRequest.java +++ b/src/main/java/com/meilisearch/sdk/SearchRequest.java @@ -22,8 +22,8 @@ public class SearchRequest { private String[] attributesToHighlight; private String[] filter; private String[][] filterArray; - private boolean matches; - private String[] facetsDistribution; + private boolean showMatchesPosition; + private String[] facets; private String[] sort; /** Empty SearchRequest constructor */ @@ -32,7 +32,7 @@ public SearchRequest() {} /** * Constructor for SearchRequest for building search queries with the default values: offset: 0, * limit: 20, attributesToRetrieve: ["*"], attributesToCrop: null, cropLength: 200, - * attributesToHighlight: null, filter: null, matches: false, facetsDistribution: null, sort: + * attributesToHighlight: null, filter: null, showMatchesPosition: false, facets: null, sort: * null * * @param q Query String @@ -44,7 +44,7 @@ public SearchRequest(String q) { /** * Constructor for SearchRequest for building search queries with the default values: limit: 20, * attributesToRetrieve: ["*"], attributesToCrop: null, cropLength: 200, attributesToHighlight: - * null, filter: null, matches: false, facetsDistribution: null, sort: null + * null, filter: null, showMatchesPosition: false, facets: null, sort: null * * @param q Query String * @param offset Number of documents to skip @@ -56,7 +56,7 @@ public SearchRequest(String q, int offset) { /** * Constructor for SearchRequest for building search queries with the default values: * attributesToRetrieve: ["*"], attributesToCrop: null, cropLength: 200, attributesToHighlight: - * null, filter: null, matches: false, facetsDistribution: null, sort: null + * null, filter: null, showMatchesPosition: false, facets: null, sort: null * * @param q Query String * @param offset Number of documents to skip @@ -68,8 +68,8 @@ public SearchRequest(String q, int offset, int limit) { /** * Constructor for SearchRequest for building search queries with the default values: - * attributesToCrop: null, cropLength: 200, attributesToHighlight: null, filter: null, matches: - * false, facetsDistribution: null, sort: null + * attributesToCrop: null, cropLength: 200, attributesToHighlight: null, filter: null, + * showMatchesPosition: false, facets: null, sort: null * * @param q Query String * @param offset Number of documents to skip @@ -105,9 +105,9 @@ public SearchRequest(String q, int offset, int limit, String[] attributesToRetri * @param cropLength Length used to crop field values * @param attributesToHighlight Attributes whose values will contain highlighted matching terms * @param filter Filter queries by an attribute value - * @param matches Defines whether an object that contains information about the matches should - * be returned or not - * @param facetsDistribution Facets for which to retrieve the matching count + * @param showMatchesPosition Defines whether an object that contains information about the + * matches should be returned or not + * @param facets Facets for which to retrieve the matching count * @param sort Sort queries by an attribute value */ public SearchRequest( @@ -119,8 +119,8 @@ public SearchRequest( int cropLength, String[] attributesToHighlight, String[] filter, - boolean matches, - String[] facetsDistribution, + boolean showMatchesPosition, + String[] facets, String[] sort) { this( q, @@ -135,8 +135,8 @@ public SearchRequest( attributesToHighlight, filter, null, - matches, - facetsDistribution, + showMatchesPosition, + facets, sort); } @@ -154,9 +154,9 @@ public SearchRequest( * @param highlightPostTag String to customize highlight tag after every highlighted query terms * @param attributesToHighlight Attributes whose values will contain highlighted matching terms * @param filter Filter queries by an attribute value - * @param matches Defines whether an object that contains information about the matches should - * be returned or not - * @param facetsDistribution Facets for which to retrieve the matching count + * @param showMatchesPosition Defines whether an object that contains information about the + * matches should be returned or not + * @param facets Facets for which to retrieve the matching count * @param sort Sort queries by an attribute value */ public SearchRequest( @@ -171,8 +171,8 @@ public SearchRequest( String highlightPostTag, String[] attributesToHighlight, String[] filter, - boolean matches, - String[] facetsDistribution, + boolean showMatchesPosition, + String[] facets, String[] sort) { this( q, @@ -187,8 +187,8 @@ public SearchRequest( attributesToHighlight, filter, null, - matches, - facetsDistribution, + showMatchesPosition, + facets, sort); } @@ -203,9 +203,9 @@ public SearchRequest( * @param cropLength Length used to crop field values * @param attributesToHighlight Attributes whose values will contain highlighted matching terms * @param filterArray String array that can take multiple nested filters - * @param matches Defines whether an object that contains information about the matches should - * be returned or not - * @param facetsDistribution Facets for which to retrieve the matching count + * @param showMatchesPosition Defines whether an object that contains information about the + * matches should be returned or not + * @param facets Facets for which to retrieve the matching count * @param sort Sort queries by an attribute value */ public SearchRequest( @@ -217,8 +217,8 @@ public SearchRequest( int cropLength, String[] attributesToHighlight, String[][] filterArray, - boolean matches, - String[] facetsDistribution, + boolean showMatchesPosition, + String[] facets, String[] sort) { this( q, @@ -233,8 +233,8 @@ public SearchRequest( attributesToHighlight, null, filterArray, - matches, - facetsDistribution, + showMatchesPosition, + facets, sort); } @@ -252,9 +252,9 @@ public SearchRequest( * @param highlightPostTag String to customize highlight tag after every highlighted query terms * @param attributesToHighlight Attributes whose values will contain highlighted matching terms * @param filterArray String array that can take multiple nested filters - * @param matches Defines whether an object that contains information about the matches should - * be returned or not - * @param facetsDistribution Facets for which to retrieve the matching count + * @param showMatchesPosition Defines whether an object that contains information about the + * matches should be returned or not + * @param facets Facets for which to retrieve the matching count * @param sort Sort queries by an attribute value */ public SearchRequest( @@ -269,8 +269,8 @@ public SearchRequest( String highlightPostTag, String[] attributesToHighlight, String[][] filterArray, - boolean matches, - String[] facetsDistribution, + boolean showMatchesPosition, + String[] facets, String[] sort) { this( q, @@ -285,8 +285,8 @@ public SearchRequest( attributesToHighlight, null, filterArray, - matches, - facetsDistribution, + showMatchesPosition, + facets, sort); } @@ -303,8 +303,8 @@ private SearchRequest( String[] attributesToHighlight, String[] filter, String[][] filterArray, - boolean matches, - String[] facetsDistribution, + boolean showMatchesPosition, + String[] facets, String[] sort) { this.q = q; this.offset = offset; @@ -318,8 +318,8 @@ private SearchRequest( this.attributesToHighlight = attributesToHighlight; this.setFilter(filter); this.setFilterArray(filterArray); - this.matches = matches; - this.facetsDistribution = facetsDistribution; + this.showMatchesPosition = showMatchesPosition; + this.facets = facets; this.sort = sort; } @@ -352,8 +352,8 @@ public String toString() { .put("cropMarker", this.cropMarker) .put("highlightPreTag", this.highlightPreTag) .put("highlightPostTag", this.highlightPostTag) - .put("matches", this.matches) - .put("facetsDistribution", this.facetsDistribution) + .put("showMatchesPosition", this.showMatchesPosition) + .put("facets", this.facets) .put("sort", this.sort) .putOpt("attributesToCrop", this.attributesToCrop) .putOpt("attributesToHighlight", this.attributesToHighlight) diff --git a/src/main/java/com/meilisearch/sdk/SettingsHandler.java b/src/main/java/com/meilisearch/sdk/SettingsHandler.java index 74a91411..e0b4785e 100644 --- a/src/main/java/com/meilisearch/sdk/SettingsHandler.java +++ b/src/main/java/com/meilisearch/sdk/SettingsHandler.java @@ -1,8 +1,9 @@ package com.meilisearch.sdk; import com.meilisearch.sdk.exceptions.MeilisearchException; +import com.meilisearch.sdk.http.URLBuilder; import com.meilisearch.sdk.model.Settings; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; import com.meilisearch.sdk.model.TypoTolerance; import java.util.Map; @@ -19,7 +20,7 @@ public class SettingsHandler { * * @param config Meilisearch configuration */ - SettingsHandler(Config config) { + protected SettingsHandler(Config config) { httpClient = config.httpClient; } @@ -31,8 +32,7 @@ public class SettingsHandler { * @throws MeilisearchException if an error occurs */ Settings getSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings"; - return httpClient.get(urlPath, Settings.class); + return httpClient.get(settingsPath(uid).getURL(), Settings.class); } /** @@ -40,24 +40,22 @@ Settings getSettings(String uid) throws MeilisearchException { * * @param uid Index identifier * @param settings the data that contains the new settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateSettings(String uid, Settings settings) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings"; - return httpClient.post(urlPath, settings, Task.class); + TaskInfo updateSettings(String uid, Settings settings) throws MeilisearchException { + return httpClient.patch(settingsPath(uid).getURL(), settings, TaskInfo.class); } /** * Resets the settings of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetSettings(String uid) throws MeilisearchException { + return httpClient.delete(settingsPath(uid).getURL(), TaskInfo.class); } /** @@ -68,8 +66,8 @@ Task resetSettings(String uid) throws MeilisearchException { * @throws MeilisearchException if an error occurs */ String[] getRankingRuleSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/ranking-rules"; - return httpClient.get(urlPath, String[].class); + return httpClient.get( + settingsPath(uid).addSubroute("ranking-rules").getURL(), String[].class); } /** @@ -77,27 +75,27 @@ String[] getRankingRuleSettings(String uid) throws MeilisearchException { * * @param uid Index identifier * @param rankingRules the data that contains the new settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateRankingRuleSettings(String uid, String[] rankingRules) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/ranking-rules"; - return httpClient.post( - urlPath, + TaskInfo updateRankingRuleSettings(String uid, String[] rankingRules) + throws MeilisearchException { + return httpClient.put( + settingsPath(uid).addSubroute("ranking-rules").getURL(), rankingRules == null ? httpClient.jsonHandler.encode(rankingRules) : rankingRules, - Task.class); + TaskInfo.class); } /** * Resets the ranking rules settings of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetRankingRulesSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/ranking-rules"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetRankingRulesSettings(String uid) throws MeilisearchException { + return httpClient.delete( + settingsPath(uid).addSubroute("ranking-rules").getURL(), TaskInfo.class); } /** @@ -108,8 +106,9 @@ Task resetRankingRulesSettings(String uid) throws MeilisearchException { * @throws MeilisearchException if an error occurs */ Map getSynonymsSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/synonyms"; - return httpClient.jsonHandler.decode(httpClient.get(urlPath, String.class), Map.class); + return httpClient.jsonHandler.decode( + httpClient.get(settingsPath(uid).addSubroute("synonyms").getURL(), String.class), + Map.class); } /** @@ -117,28 +116,27 @@ Map getSynonymsSettings(String uid) throws MeilisearchExceptio * * @param uid Index identifier * @param synonyms a Map that contains the new synonyms settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateSynonymsSettings(String uid, Map synonyms) + TaskInfo updateSynonymsSettings(String uid, Map synonyms) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/synonyms"; - return httpClient.post( - urlPath, + return httpClient.put( + settingsPath(uid).addSubroute("synonyms").getURL(), synonyms == null ? httpClient.jsonHandler.encode(synonyms) : synonyms, - Task.class); + TaskInfo.class); } /** * Resets the synonyms settings of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetSynonymsSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/synonyms"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetSynonymsSettings(String uid) throws MeilisearchException { + return httpClient.delete( + settingsPath(uid).addSubroute("synonyms").getURL(), TaskInfo.class); } /** @@ -149,8 +147,7 @@ Task resetSynonymsSettings(String uid) throws MeilisearchException { * @throws MeilisearchException if an error occurs */ String[] getStopWordsSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/stop-words"; - return httpClient.get(urlPath, String[].class); + return httpClient.get(settingsPath(uid).addSubroute("stop-words").getURL(), String[].class); } /** @@ -158,27 +155,26 @@ String[] getStopWordsSettings(String uid) throws MeilisearchException { * * @param uid Index identifier * @param stopWords an array of strings that contains the new stop-words settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateStopWordsSettings(String uid, String[] stopWords) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/stop-words"; - return httpClient.post( - urlPath, + TaskInfo updateStopWordsSettings(String uid, String[] stopWords) throws MeilisearchException { + return httpClient.put( + settingsPath(uid).addSubroute("stop-words").getURL(), stopWords == null ? httpClient.jsonHandler.encode(stopWords) : stopWords, - Task.class); + TaskInfo.class); } /** * Resets the stop-words settings of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetStopWordsSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/stop-words"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetStopWordsSettings(String uid) throws MeilisearchException { + return httpClient.delete( + settingsPath(uid).addSubroute("stop-words").getURL(), TaskInfo.class); } /** @@ -189,8 +185,8 @@ Task resetStopWordsSettings(String uid) throws MeilisearchException { * @throws MeilisearchException if an error occurs */ String[] getSearchableAttributesSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/searchable-attributes"; - return httpClient.get(urlPath, String[].class); + return httpClient.get( + settingsPath(uid).addSubroute("searchable-attributes").getURL(), String[].class); } /** @@ -199,30 +195,29 @@ String[] getSearchableAttributesSettings(String uid) throws MeilisearchException * @param uid Index identifier * @param searchableAttributes an array of strings that contains the new searchable attributes * settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateSearchableAttributesSettings(String uid, String[] searchableAttributes) + TaskInfo updateSearchableAttributesSettings(String uid, String[] searchableAttributes) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/searchable-attributes"; - return httpClient.post( - urlPath, + return httpClient.put( + settingsPath(uid).addSubroute("searchable-attributes").getURL(), searchableAttributes == null ? httpClient.jsonHandler.encode(searchableAttributes) : searchableAttributes, - Task.class); + TaskInfo.class); } /** * Resets the searchable attributes of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetSearchableAttributesSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/searchable-attributes"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetSearchableAttributesSettings(String uid) throws MeilisearchException { + return httpClient.delete( + settingsPath(uid).addSubroute("searchable-attributes").getURL(), TaskInfo.class); } /** @@ -233,8 +228,8 @@ Task resetSearchableAttributesSettings(String uid) throws MeilisearchException { * @throws MeilisearchException if an error occurs */ String[] getDisplayedAttributesSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/displayed-attributes"; - return httpClient.get(urlPath, String[].class); + return httpClient.get( + settingsPath(uid).addSubroute("displayed-attributes").getURL(), String[].class); } /** @@ -243,30 +238,29 @@ String[] getDisplayedAttributesSettings(String uid) throws MeilisearchException * @param uid Index identifier * @param displayAttributes an array of strings that contains the new displayed attributes * settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateDisplayedAttributesSettings(String uid, String[] displayAttributes) + TaskInfo updateDisplayedAttributesSettings(String uid, String[] displayAttributes) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/displayed-attributes"; - return httpClient.post( - urlPath, + return httpClient.put( + settingsPath(uid).addSubroute("displayed-attributes").getURL(), displayAttributes == null ? httpClient.jsonHandler.encode(displayAttributes) : displayAttributes, - Task.class); + TaskInfo.class); } /** * Resets the displayed attributes of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetDisplayedAttributesSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/displayed-attributes"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetDisplayedAttributesSettings(String uid) throws MeilisearchException { + return httpClient.delete( + settingsPath(uid).addSubroute("displayed-attributes").getURL(), TaskInfo.class); } /** @@ -277,8 +271,8 @@ Task resetDisplayedAttributesSettings(String uid) throws MeilisearchException { * @throws MeilisearchException if an error occurs */ String[] getFilterableAttributesSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/filterable-attributes"; - return httpClient.get(urlPath, String[].class); + return httpClient.get( + settingsPath(uid).addSubroute("filterable-attributes").getURL(), String[].class); } /** @@ -287,30 +281,29 @@ String[] getFilterableAttributesSettings(String uid) throws MeilisearchException * @param uid Index identifier * @param filterableAttributes an array of strings that contains the new filterable attributes * settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateFilterableAttributesSettings(String uid, String[] filterableAttributes) + TaskInfo updateFilterableAttributesSettings(String uid, String[] filterableAttributes) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/filterable-attributes"; - return httpClient.post( - urlPath, + return httpClient.put( + settingsPath(uid).addSubroute("filterable-attributes").getURL(), filterableAttributes == null ? httpClient.jsonHandler.encode(filterableAttributes) : filterableAttributes, - Task.class); + TaskInfo.class); } /** * Resets the filterable attributes of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetFilterableAttributesSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/filterable-attributes"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetFilterableAttributesSettings(String uid) throws MeilisearchException { + return httpClient.delete( + settingsPath(uid).addSubroute("filterable-attributes").getURL(), TaskInfo.class); } /** @@ -321,8 +314,9 @@ Task resetFilterableAttributesSettings(String uid) throws MeilisearchException { * @throws MeilisearchException if an error occurs */ String getDistinctAttributeSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/distinct-attribute"; - String response = httpClient.get(urlPath, String.class); + String response = + httpClient.get( + settingsPath(uid).addSubroute("distinct-attribute").getURL(), String.class); return response.equals("null") ? null : response.substring(1, response.length() - 1); } @@ -331,30 +325,29 @@ String getDistinctAttributeSettings(String uid) throws MeilisearchException { * * @param uid Index identifier * @param distinctAttribute a String that contains the new distinct attributes settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateDistinctAttributeSettings(String uid, String distinctAttribute) + TaskInfo updateDistinctAttributeSettings(String uid, String distinctAttribute) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/distinct-attribute"; - return httpClient.post( - urlPath, + return httpClient.put( + settingsPath(uid).addSubroute("distinct-attribute").getURL(), distinctAttribute == null ? httpClient.jsonHandler.encode(distinctAttribute) : "\"" + distinctAttribute + "\"", - Task.class); + TaskInfo.class); } /** * Resets the distinct attribute field of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetDistinctAttributeSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/distinct-attribute"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetDistinctAttributeSettings(String uid) throws MeilisearchException { + return httpClient.delete( + settingsPath(uid).addSubroute("distinct-attribute").getURL(), TaskInfo.class); } /** @@ -365,8 +358,8 @@ Task resetDistinctAttributeSettings(String uid) throws MeilisearchException { * @throws MeilisearchException if an error occurs */ TypoTolerance getTypoToleranceSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/typo-tolerance"; - return httpClient.get(urlPath, TypoTolerance.class); + return httpClient.get( + settingsPath(uid).addSubroute("typo-tolerance").getURL(), TypoTolerance.class); } /** @@ -374,29 +367,33 @@ TypoTolerance getTypoToleranceSettings(String uid) throws MeilisearchException { * * @param uid Index identifier * @param typoTolerance a TypoTolerance instance that contains the new typo tolerance settings - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task updateTypoToleranceSettings(String uid, TypoTolerance typoTolerance) + TaskInfo updateTypoToleranceSettings(String uid, TypoTolerance typoTolerance) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/typo-tolerance"; - return httpClient.post( - urlPath, + return httpClient.patch( + settingsPath(uid).addSubroute("typo-tolerance").getURL(), typoTolerance == null ? httpClient.jsonHandler.encode(typoTolerance) : typoTolerance, - Task.class); + TaskInfo.class); } /** * Resets the typo tolerance settings of the index * * @param uid Index identifier - * @return Task instance + * @return TaskInfo instance * @throws MeilisearchException if an error occurs */ - Task resetTypoToleranceSettings(String uid) throws MeilisearchException { - String urlPath = "/indexes/" + uid + "/settings/typo-tolerance"; - return httpClient.delete(urlPath, Task.class); + TaskInfo resetTypoToleranceSettings(String uid) throws MeilisearchException { + return httpClient.delete( + settingsPath(uid).addSubroute("typo-tolerance").getURL(), TaskInfo.class); + } + + /** Creates an URLBuilder for the constant route settings */ + private URLBuilder settingsPath(String uid) { + return new URLBuilder("/indexes").addSubroute(uid).addSubroute("/settings"); } } diff --git a/src/main/java/com/meilisearch/sdk/TasksHandler.java b/src/main/java/com/meilisearch/sdk/TasksHandler.java index 81301cbd..637aaf10 100644 --- a/src/main/java/com/meilisearch/sdk/TasksHandler.java +++ b/src/main/java/com/meilisearch/sdk/TasksHandler.java @@ -2,8 +2,10 @@ import com.meilisearch.sdk.exceptions.MeilisearchException; import com.meilisearch.sdk.exceptions.MeilisearchTimeoutException; -import com.meilisearch.sdk.model.Result; +import com.meilisearch.sdk.http.URLBuilder; import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TasksQuery; +import com.meilisearch.sdk.model.TasksResults; import java.util.Date; /** @@ -21,59 +23,80 @@ public class TasksHandler { * * @param config MeiliSearch configuration */ - TasksHandler(Config config) { + protected TasksHandler(Config config) { this.httpClient = config.httpClient; } /** - * Retrieves the task at the specified index uid with the specified task uid + * Retrieves one task with the specified task uid * - * @param indexUid Index identifier to the requested Task * @param taskUid Identifier of the requested Task * @return Task instance * @throws MeilisearchException if client request causes an error */ - Task getTask(String indexUid, int taskUid) throws MeilisearchException { - String urlPath = "/indexes/" + indexUid + "/tasks/" + taskUid; + Task getTask(int taskUid) throws MeilisearchException { + URLBuilder urlb = new URLBuilder(); + urlb.addSubroute("tasks").addSubroute(Integer.toString(taskUid)); + String urlPath = urlb.getURL(); return httpClient.get(urlPath, Task.class); } /** - * Retrieves all TasksHandler at the specified index uid + * Retrieves all tasks from the client * - * @param indexUid Index identifier to the requested Tasks - * @return List of task instance + * @return TasksResults containing a list of task instance * @throws MeilisearchException if client request causes an error */ - Result getTasks(String indexUid) throws MeilisearchException { - String urlPath = "/indexes/" + indexUid + "/tasks"; + TasksResults getTasks() throws MeilisearchException { + TasksResults result = httpClient.get(tasksPath().getURL(), TasksResults.class); + return result; + } - Result result = httpClient.get(urlPath, Result.class, Task.class); + /** + * Retrieves all tasks from the client + * + * @param param accept by the tasks route + * @return TasksResults containing a list of task instance + * @throws MeilisearchException if client request causes an error + */ + TasksResults getTasks(TasksQuery param) throws MeilisearchException { + TasksResults result = + httpClient.get(tasksPath().addQuery(param.toQuery()).getURL(), TasksResults.class); return result; } /** - * Retrieves the task with the specified task uid + * Retrieves all tasks from specified index uid * - * @param taskUid Identifier of the requested Task - * @return Task instance + * @param indexUid Index identifier to index of the requested Tasks + * @return TasksResults containing a list of task instance * @throws MeilisearchException if client request causes an error */ - Task getTask(int taskUid) throws MeilisearchException { - String urlPath = "/tasks/" + taskUid; - return httpClient.get(urlPath, Task.class); + TasksResults getTasks(String indexUid) throws MeilisearchException { + URLBuilder urlb = tasksPath().addParameter("indexUid", indexUid); + + TasksResults result = httpClient.get(urlb.getURL(), TasksResults.class); + return result; } /** - * Retrieves tasks from the client + * Retrieves all tasks from specified index uid * - * @return List of task instance + * @param indexUid Index identifier to index of the requested Tasks + * @param param accept by the tasks route + * @return TasksResults containing a list of task instance * @throws MeilisearchException if client request causes an error */ - Result getTasks() throws MeilisearchException { - String urlPath = "/tasks"; + TasksResults getTasks(String indexUid, TasksQuery param) throws MeilisearchException { + String[] newIndexUid = new String[param.getIndexUid().length + 1]; + if (param != null && param.getIndexUid() != null) { + for (int i = 0; i < param.getIndexUid().length; i++) + newIndexUid[i] = param.getIndexUid()[i]; + newIndexUid[param.getIndexUid().length] = indexUid; + } - Result result = httpClient.get(urlPath, Result.class, Task.class); + TasksResults result = + httpClient.get(tasksPath().addQuery(param.toQuery()).getURL(), TasksResults.class); return result; } @@ -115,4 +138,9 @@ void waitForTask(int taskUid, int timeoutInMs, int intervalInMs) throws Meilisea elapsedTime = new Date().getTime() - startTime; } } + + /** Creates an URLBuilder for the constant route tasks */ + private URLBuilder tasksPath() { + return new URLBuilder("/tasks"); + } } diff --git a/src/main/java/com/meilisearch/sdk/http/URLBuilder.java b/src/main/java/com/meilisearch/sdk/http/URLBuilder.java new file mode 100644 index 00000000..180f33e6 --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/http/URLBuilder.java @@ -0,0 +1,76 @@ +package com.meilisearch.sdk.http; + +import lombok.Getter; + +@Getter +public class URLBuilder { + private StringBuilder routes, params; + + public URLBuilder() { + routes = new StringBuilder(); + params = new StringBuilder(); + } + + public URLBuilder(String rootRoute) { + routes = new StringBuilder(rootRoute); + params = new StringBuilder(); + } + + public URLBuilder addSubroute(String route) { + routes.append("/"); + routes.append(route); + return this; + } + + public URLBuilder addParameter(String parameter, String value) { + if (value != "") { + addSeparator(); + params.append(parameter); + params.append("="); + params.append(value); + } + return this; + } + + public URLBuilder addParameter(String parameter, int value) { + if (value > -1) { + addSeparator(); + params.append(parameter); + params.append("="); + params.append(value); + } + return this; + } + + public URLBuilder addParameter(String parameter, String[] value) { + if (value != null && value.length > 0) { + addSeparator(); + params.append(parameter); + params.append("="); + params.append(formatArrayParameters(value)); + } + return this; + } + + public URLBuilder addQuery(String query) { + this.params.append(query); + return this; + } + + private URLBuilder addSeparator() { + if (params.length() > 0) { + params.append("&"); + } else { + params.append("?"); + } + return this; + } + + private String formatArrayParameters(String[] fields) { + return String.join(",", fields); + } + + public String getURL() { + return routes.toString() + params.toString(); + } +} diff --git a/src/main/java/com/meilisearch/sdk/json/GsonJsonHandler.java b/src/main/java/com/meilisearch/sdk/json/GsonJsonHandler.java index 3c9eeee5..10cbf1e4 100644 --- a/src/main/java/com/meilisearch/sdk/json/GsonJsonHandler.java +++ b/src/main/java/com/meilisearch/sdk/json/GsonJsonHandler.java @@ -2,6 +2,9 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import com.meilisearch.sdk.exceptions.JsonDecodingException; @@ -26,9 +29,20 @@ public String encode(Object o) throws MeilisearchException { return (String) o; } // TODO: review later + // This is a workaround to encode the Key class properly if (o != null && o.getClass() == Key.class) { GsonBuilder builder = new GsonBuilder(); - this.gson = builder.serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").create(); + this.gson = builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").create(); + + Key key = (Key) o; + if (key.getExpiresAt() == null) { + JsonElement jsonElement = gson.toJsonTree(o); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + jsonObject.add("expiresAt", JsonNull.INSTANCE); + o = jsonObject; + this.gson = + builder.serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").create(); + } } try { return gson.toJson(o); @@ -52,7 +66,7 @@ public T decode(Object o, Class targetClass, Class... parameters) return gson.fromJson((String) o, targetClass); } else { TypeToken parameterized = TypeToken.getParameterized(targetClass, parameters); - return gson.fromJson((String) o, parameterized.getType()); + return gson.fromJson((String) o, parameterized.getType()); } } catch (JsonSyntaxException e) { throw new JsonDecodingException(e); diff --git a/src/main/java/com/meilisearch/sdk/model/DocumentQuery.java b/src/main/java/com/meilisearch/sdk/model/DocumentQuery.java new file mode 100644 index 00000000..5cc05f32 --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/DocumentQuery.java @@ -0,0 +1,23 @@ +package com.meilisearch.sdk.model; + +import com.meilisearch.sdk.http.URLBuilder; +import lombok.Getter; +import lombok.Setter; + +/** + * Data structure of the query parameters of the documents route when retrieving a document + * + *

https://docs.meilisearch.com/reference/api/documents.html#query-parameters + */ +@Setter +@Getter +public class DocumentQuery { + private String[] fields; + + public DocumentQuery() {} + + public String toQuery() { + URLBuilder urlb = new URLBuilder().addParameter("fields", this.getFields()); + return urlb.getURL(); + } +} diff --git a/src/main/java/com/meilisearch/sdk/model/DocumentsQuery.java b/src/main/java/com/meilisearch/sdk/model/DocumentsQuery.java new file mode 100644 index 00000000..8493cd5d --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/DocumentsQuery.java @@ -0,0 +1,31 @@ +package com.meilisearch.sdk.model; + +import com.meilisearch.sdk.http.URLBuilder; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +/** + * Data structure of the query parameters of the documents route when retrieving multiple documents + * + *

https://docs.meilisearch.com/reference/api/documents.html#query-parameters + */ +@Setter +@Getter +@Accessors(chain = true) +public class DocumentsQuery { + private int offset = -1; + private int limit = -1; + private String[] fields; + + public DocumentsQuery() {} + + public String toQuery() { + URLBuilder urlb = + new URLBuilder() + .addParameter("limit", this.getLimit()) + .addParameter("offset", this.getOffset()) + .addParameter("fields", this.getFields()); + return urlb.getURL(); + } +} diff --git a/src/main/java/com/meilisearch/sdk/model/IndexesQuery.java b/src/main/java/com/meilisearch/sdk/model/IndexesQuery.java new file mode 100644 index 00000000..8651bdd6 --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/IndexesQuery.java @@ -0,0 +1,29 @@ +package com.meilisearch.sdk.model; + +import com.meilisearch.sdk.http.URLBuilder; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +/** + * Data structure of the query parameters when fetching indexes + * + *

https://docs.meilisearch.com/reference/api/indexes.html#query-parameters + */ +@Setter +@Getter +@Accessors(chain = true) +public class IndexesQuery { + private int offset = -1; + private int limit = -1; + + public IndexesQuery() {} + + public String toQuery() { + URLBuilder urlb = + new URLBuilder() + .addParameter("limit", this.getLimit()) + .addParameter("offset", this.getOffset()); + return urlb.getURL(); + } +} diff --git a/src/main/java/com/meilisearch/sdk/model/Key.java b/src/main/java/com/meilisearch/sdk/model/Key.java index 110a91ea..7a3d8a8e 100644 --- a/src/main/java/com/meilisearch/sdk/model/Key.java +++ b/src/main/java/com/meilisearch/sdk/model/Key.java @@ -12,11 +12,17 @@ */ @Getter public class Key { + @Setter + @Accessors(chain = true) + protected String name = null; + @Setter @Accessors(chain = true) protected String description = null; - protected String key = ""; + protected String uid = null; + + protected String key = null; @Setter @Accessors(chain = true) diff --git a/src/main/java/com/meilisearch/sdk/model/KeyUpdate.java b/src/main/java/com/meilisearch/sdk/model/KeyUpdate.java new file mode 100644 index 00000000..42c02802 --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/KeyUpdate.java @@ -0,0 +1,23 @@ +package com.meilisearch.sdk.model; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +/** + * Data structure for updating a Key + * + *

https://docs.meilisearch.com/reference/api/keys.html + */ +@Getter +public class KeyUpdate { + @Setter + @Accessors(chain = true) + protected String name = null; + + @Setter + @Accessors(chain = true) + protected String description = null; + + public KeyUpdate() {} +} diff --git a/src/main/java/com/meilisearch/sdk/model/KeysQuery.java b/src/main/java/com/meilisearch/sdk/model/KeysQuery.java new file mode 100644 index 00000000..d1c9d7e9 --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/KeysQuery.java @@ -0,0 +1,29 @@ +package com.meilisearch.sdk.model; + +import com.meilisearch.sdk.http.URLBuilder; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +/** + * Data structure of the query parameters for the keys routes + * + *

https://docs.meilisearch.com/reference/api/keys.html#query-parameters + */ +@Setter +@Getter +@Accessors(chain = true) +public class KeysQuery { + private int offset = -1; + private int limit = -1; + + public KeysQuery() {} + + public String toQuery() { + URLBuilder urlb = + new URLBuilder() + .addParameter("limit", this.getLimit()) + .addParameter("offset", this.getOffset()); + return urlb.getURL(); + } +} diff --git a/src/main/java/com/meilisearch/sdk/model/Result.java b/src/main/java/com/meilisearch/sdk/model/Result.java deleted file mode 100644 index 84877804..00000000 --- a/src/main/java/com/meilisearch/sdk/model/Result.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.meilisearch.sdk.model; - -import lombok.Getter; - -/** Data structure of Meilisearch response for a Result */ -@Getter -public class Result { - protected T[] results = null; - - public Result() {} -} diff --git a/src/main/java/com/meilisearch/sdk/model/Results.java b/src/main/java/com/meilisearch/sdk/model/Results.java new file mode 100644 index 00000000..88e2615d --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/Results.java @@ -0,0 +1,14 @@ +package com.meilisearch.sdk.model; + +import lombok.Getter; + +/** Data structure of Meilisearch response for a Results */ +@Getter +public class Results { + protected T[] results = null; + protected int limit; + protected int offset; + protected int total; + + public Results() {} +} diff --git a/src/main/java/com/meilisearch/sdk/model/SearchResult.java b/src/main/java/com/meilisearch/sdk/model/SearchResult.java index c88f64da..2e8c0ced 100644 --- a/src/main/java/com/meilisearch/sdk/model/SearchResult.java +++ b/src/main/java/com/meilisearch/sdk/model/SearchResult.java @@ -17,10 +17,8 @@ public class SearchResult implements Serializable { protected ArrayList> hits; protected int offset; protected int limit; - protected int nbHits; - protected boolean exhaustiveNbHits; - protected Object facetsDistribution; - protected boolean exhaustiveFacetsCount; + protected int estimatedTotalHits; + protected Object facetDistribution; protected int processingTimeMs; protected String query; diff --git a/src/main/java/com/meilisearch/sdk/model/TaskInfo.java b/src/main/java/com/meilisearch/sdk/model/TaskInfo.java new file mode 100644 index 00000000..dde50fc6 --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/TaskInfo.java @@ -0,0 +1,26 @@ +package com.meilisearch.sdk.model; + +import com.meilisearch.sdk.TaskError; +import java.util.Date; +import lombok.Getter; + +/** + * Data structure of Meilisearch response for a asynchronous operation + * + *

https://docs.meilisearch.com/reference/api/tasks.html + */ +@Getter +public class TaskInfo { + protected String status = ""; + protected int taskUid = 0; + protected String indexUid = ""; + protected String type = null; + protected String duration = ""; + protected Date enqueuedAt = null; + protected Date startedAt = null; + protected Date finishedAt = null; + protected TaskError error = null; + protected TaskDetails details = null; + + public TaskInfo() {} +} diff --git a/src/main/java/com/meilisearch/sdk/model/TasksQuery.java b/src/main/java/com/meilisearch/sdk/model/TasksQuery.java new file mode 100644 index 00000000..43326615 --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/TasksQuery.java @@ -0,0 +1,35 @@ +package com.meilisearch.sdk.model; + +import com.meilisearch.sdk.http.URLBuilder; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +/** + * Data structure of a query parameter for tasks route + * + *

https://docs.meilisearch.com/reference/api/tasks.html#query-parameters + */ +@Setter +@Getter +@Accessors(chain = true) +public class TasksQuery { + private int limit = -1; + private int from = -1; + private String[] status; + private String[] type; + private String[] indexUid; + + public TasksQuery() {} + + public String toQuery() { + URLBuilder urlb = + new URLBuilder() + .addParameter("limit", this.getLimit()) + .addParameter("from", this.getFrom()) + .addParameter("status", this.getStatus()) + .addParameter("type", this.getType()) + .addParameter("indexUid", this.getIndexUid()); + return urlb.getURL(); + } +} diff --git a/src/main/java/com/meilisearch/sdk/model/TasksResults.java b/src/main/java/com/meilisearch/sdk/model/TasksResults.java new file mode 100644 index 00000000..5ee0b52e --- /dev/null +++ b/src/main/java/com/meilisearch/sdk/model/TasksResults.java @@ -0,0 +1,18 @@ +package com.meilisearch.sdk.model; + +import lombok.Getter; + +/** + * Data structure of Meilisearch response for tasks Results + * + *

https://docs.meilisearch.com/reference/api/tasks.html#response + */ +@Getter +public class TasksResults { + protected Task[] results = null; + protected int limit; + protected int from; + protected int next; + + public TasksResults() {} +} diff --git a/src/main/java/com/meilisearch/sdk/TenantTokenOptions.java b/src/main/java/com/meilisearch/sdk/model/TenantTokenOptions.java similarity index 100% rename from src/main/java/com/meilisearch/sdk/TenantTokenOptions.java rename to src/main/java/com/meilisearch/sdk/model/TenantTokenOptions.java diff --git a/src/test/java/com/meilisearch/integration/ClientTest.java b/src/test/java/com/meilisearch/integration/ClientTest.java index 8c751baf..a9561e36 100644 --- a/src/test/java/com/meilisearch/integration/ClientTest.java +++ b/src/test/java/com/meilisearch/integration/ClientTest.java @@ -9,7 +9,10 @@ import com.meilisearch.integration.classes.TestData; import com.meilisearch.sdk.Index; import com.meilisearch.sdk.exceptions.MeilisearchApiException; +import com.meilisearch.sdk.model.IndexesQuery; +import com.meilisearch.sdk.model.Results; import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; import com.meilisearch.sdk.utils.Movie; import java.util.Arrays; import org.junit.jupiter.api.AfterAll; @@ -28,6 +31,7 @@ public void initialize() { setUp(); setUpJacksonClient(); if (testData == null) testData = this.getTestData(MOVIES_INDEX, Movie.class); + cleanup(); } @AfterAll @@ -43,22 +47,18 @@ public void testCreateIndexWithoutPrimaryKey() throws Exception { assertEquals(index.getUid(), indexUid); assertNull(index.getPrimaryKey()); - - client.deleteIndex(index.getUid()); } /** Test Index creation without PrimaryKey with Jackson Json Handler */ @Test public void testCreateIndexWithoutPrimaryKeyWithJacksonJsonHandler() throws Exception { String indexUid = "CreateIndexWithoutPrimaryKeyWithJacksonJsonHandler"; - Task task = clientJackson.createIndex(indexUid); - clientJackson.waitForTask(task.getUid()); + TaskInfo task = clientJackson.createIndex(indexUid); + clientJackson.waitForTask(task.getTaskUid()); Index index = clientJackson.getIndex(indexUid); assertEquals(index.getUid(), indexUid); assertNull(index.getPrimaryKey()); - - clientJackson.deleteIndex(index.getUid()); } /** Test Index creation with PrimaryKey */ @@ -69,22 +69,18 @@ public void testCreateIndexWithPrimaryKey() throws Exception { assertEquals(index.getUid(), indexUid); assertEquals(index.getPrimaryKey(), this.primaryKey); - - client.deleteIndex(index.getUid()); } /** Test Index creation with PrimaryKey with Jackson Json Handler */ @Test public void testCreateIndexWithPrimaryKeyWithJacksonJsonHandler() throws Exception { String indexUid = "CreateIndexWithPrimaryKeyWithJacksonJsonHandler"; - Task task = clientJackson.createIndex(indexUid, this.primaryKey); - clientJackson.waitForTask(task.getUid()); + TaskInfo task = clientJackson.createIndex(indexUid, this.primaryKey); + clientJackson.waitForTask(task.getTaskUid()); Index index = clientJackson.getIndex(indexUid); assertEquals(index.getUid(), indexUid); assertEquals(index.getPrimaryKey(), this.primaryKey); - - clientJackson.deleteIndex(index.getUid()); } /** Test Index creation twice doesn't throw an error: already exists */ @@ -102,8 +98,6 @@ public void testCreateIndexAlreadyExists() throws Exception { assertEquals(indexDuplicate.getUid(), indexUid); assertEquals(index.getPrimaryKey(), this.primaryKey); assertEquals(indexDuplicate.getPrimaryKey(), this.primaryKey); - - client.deleteIndex(index.getUid()); } /** Test update Index PrimaryKey */ @@ -115,15 +109,13 @@ public void testUpdateIndexPrimaryKey() throws Exception { assertEquals(index.getUid(), indexUid); assertNull(index.getPrimaryKey()); - Task task = client.updateIndex(indexUid, this.primaryKey); - client.waitForTask(task.getUid()); + TaskInfo task = client.updateIndex(indexUid, this.primaryKey); + client.waitForTask(task.getTaskUid()); index = client.getIndex(indexUid); assertTrue(index instanceof Index); assertEquals(index.getUid(), indexUid); assertEquals(index.getPrimaryKey(), this.primaryKey); - - client.deleteIndex(index.getUid()); } /** Test getIndex */ @@ -135,22 +127,6 @@ public void testGetIndex() throws Exception { assertEquals(index.getUid(), getIndex.getUid()); assertEquals(index.getPrimaryKey(), getIndex.getPrimaryKey()); - - client.deleteIndex(index.getUid()); - } - - /** Test getRawIndex */ - @Test - public void testGetRawIndex() throws Exception { - String indexUid = "GetRawIndex"; - Index index = createEmptyIndex(indexUid, this.primaryKey); - String getIndex = client.getRawIndex(indexUid); - JsonObject indexJson = JsonParser.parseString(getIndex).getAsJsonObject(); - - assertEquals(index.getUid(), indexJson.get("uid").getAsString()); - assertEquals(index.getPrimaryKey(), indexJson.get("primaryKey").getAsString()); - - client.deleteIndex(index.getUid()); } /** Test getIndexes */ @@ -159,14 +135,41 @@ public void testGetIndexes() throws Exception { String[] indexUids = {"GetIndexes", "GetIndexes2"}; createEmptyIndex(indexUids[0]); createEmptyIndex(indexUids[1], this.primaryKey); - Index[] indexes = client.getIndexes(); + Results indexes = client.getIndexes(); - assertEquals(2, indexes.length); + assertEquals(2, indexes.getResults().length); assert (Arrays.asList(indexUids).contains(indexUids[0])); assert (Arrays.asList(indexUids).contains(indexUids[1])); + } - client.deleteIndex(indexUids[0]); - client.deleteIndex(indexUids[1]); + /** Test getIndexes with limit */ + @Test + public void testGetIndexesLimit() throws Exception { + int limit = 1; + String[] indexUids = {"GetIndexesLimit", "GetIndexesLimit2"}; + IndexesQuery query = new IndexesQuery().setLimit(limit); + createEmptyIndex(indexUids[0]); + createEmptyIndex(indexUids[1], this.primaryKey); + Results indexes = client.getIndexes(query); + + assertEquals(limit, indexes.getResults().length); + assertEquals(limit, indexes.getLimit()); + } + + /** Test getIndexes with limit and offset */ + @Test + public void testGetIndexesLimitAndOffset() throws Exception { + int limit = 1; + int offset = 1; + String[] indexUids = {"GetIndexesLimitOffset", "GetIndexesLimitOffset2"}; + IndexesQuery query = new IndexesQuery().setLimit(limit).setOffset(offset); + createEmptyIndex(indexUids[0]); + createEmptyIndex(indexUids[1], this.primaryKey); + Results indexes = client.getIndexes(query); + + assertEquals(limit, indexes.getResults().length); + assertEquals(limit, indexes.getLimit()); + assertEquals(offset, indexes.getOffset()); } /** Test getRawIndexes */ @@ -177,16 +180,14 @@ public void testGetRawIndexes() throws Exception { createEmptyIndex(indexUids[1], this.primaryKey); String indexes = client.getRawIndexes(); - JsonArray jsonIndexArray = JsonParser.parseString(indexes).getAsJsonArray(); + JsonObject jsonIndexObject = JsonParser.parseString(indexes).getAsJsonObject(); + JsonArray jsonIndexArray = jsonIndexObject.getAsJsonArray("results"); - assertEquals(4, jsonIndexArray.size()); + assertEquals(2, jsonIndexArray.size()); assert (Arrays.asList(indexUids) .contains(jsonIndexArray.get(0).getAsJsonObject().get("uid").getAsString())); assert (Arrays.asList(indexUids) .contains(jsonIndexArray.get(1).getAsJsonObject().get("uid").getAsString())); - - client.deleteIndex(indexUids[0]); - client.deleteIndex(indexUids[1]); } /** Test deleteIndex */ @@ -194,8 +195,8 @@ public void testGetRawIndexes() throws Exception { public void testDeleteIndex() throws Exception { String indexUid = "DeleteIndex"; Index index = createEmptyIndex(indexUid); - Task task = client.deleteIndex(index.getUid()); - client.waitForTask(task.getUid()); + TaskInfo task = client.deleteIndex(index.getUid()); + client.waitForTask(task.getTaskUid()); assertThrows(MeilisearchApiException.class, () -> client.getIndex(indexUid)); } @@ -237,24 +238,14 @@ public void testIndexMethodCallExistingIndexWithPrimaryKey() throws Exception { assertEquals(primaryKey, index.getPrimaryKey()); } - // /** Test call to create dump */ - // TODO rewrite Dump test - // @Test - // public void testCreateDump() throws Exception { - // Dump dump = client.createDump(); - // String status = dump.getStatus(); - - // assertEquals(status, "in_progress"); - // } - - // /** Test call to get dump status by uid */ - // @Test - // public void testGetDumpStatus() throws Exception { - // Dump dump = client.createDump(); - // String uid = dump.getUid(); - // String status = client.getDumpStatus(uid); - - // assertNotNull(status); - // assertNotNull(uid); - // } + /** Test call to create dump */ + @Test + public void testCreateDump() throws Exception { + TaskInfo task = client.createDump(); + client.waitForTask(task.getTaskUid()); + Task dump = client.getTask(task.getTaskUid()); + + assertEquals(task.getStatus(), "enqueued"); + assertEquals("dumpCreation", dump.getType()); + } } diff --git a/src/test/java/com/meilisearch/integration/DocumentsTest.java b/src/test/java/com/meilisearch/integration/DocumentsTest.java index b46d9251..7dbab16c 100644 --- a/src/test/java/com/meilisearch/integration/DocumentsTest.java +++ b/src/test/java/com/meilisearch/integration/DocumentsTest.java @@ -1,6 +1,5 @@ package com.meilisearch.integration; -import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.*; import com.google.gson.JsonObject; @@ -8,19 +7,18 @@ import com.meilisearch.integration.classes.TestData; import com.meilisearch.sdk.Index; import com.meilisearch.sdk.exceptions.MeilisearchApiException; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.DocumentsQuery; +import com.meilisearch.sdk.model.Results; +import com.meilisearch.sdk.model.TaskInfo; import com.meilisearch.sdk.utils.Movie; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.stream.Stream; import org.jetbrains.annotations.NotNull; 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 org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; @Tag("integration") public class DocumentsTest extends AbstractIT { @@ -44,10 +42,11 @@ public void testAddDocumentsSingle() throws Exception { TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); String singleDocument = this.gson.toJson(testData.getData().get(0)); - Task task = index.addDocuments("[" + singleDocument + "]"); + TaskInfo task = index.addDocuments("[" + singleDocument + "]"); - index.waitForTask(task.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); assertEquals(1, movies.length); assertEquals("419704", movies[0].getId()); @@ -83,18 +82,19 @@ public void testAddDocumentsWithSuppliedPrimaryKey() throws Exception { String firstDocument = this.gson.toJson(firstMovie); String secondDocument = this.gson.toJson(secondMovie); - Task firstTask = index.addDocuments("[" + firstDocument + "]", "language"); - index.waitForTask(firstTask.getUid()); + TaskInfo firstTask = index.addDocuments("[" + firstDocument + "]", "language"); + index.waitForTask(firstTask.getTaskUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); assertEquals(1, movies.length); assertEquals("419704", movies[0].getId()); assertEquals("Ad Astra", movies[0].getTitle()); - Task secondTask = index.addDocuments("[" + secondDocument + "]", "language"); - index.waitForTask(secondTask.getUid()); + TaskInfo secondTask = index.addDocuments("[" + secondDocument + "]", "language"); + index.waitForTask(secondTask.getTaskUid()); - movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + movies = (Movie[]) index.getDocuments(Movie.class).getResults(); assertEquals(1, movies.length); assertEquals("574982", movies[0].getId()); assertEquals("The Blackout", movies[0].getTitle()); @@ -108,14 +108,13 @@ public void testAddDocumentsMultiple() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); for (int i = 0; i < movies.length; i++) { - Movie movie = - this.gson.fromJson( - index.getDocument(testData.getData().get(i).getId()), Movie.class); + Movie movie = index.getDocument(testData.getData().get(i).getId(), Movie.class); assertEquals(movie.getTitle(), testData.getData().get(i).getTitle()); } } @@ -128,14 +127,13 @@ public void testAddDocumentsMultipleWithJacksonJsonHandler() throws Exception { Index index = clientJackson.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); for (int i = 0; i < movies.length; i++) { - Movie movie = - this.gson.fromJson( - index.getDocument(testData.getData().get(i).getId()), Movie.class); + Movie movie = index.getDocument(testData.getData().get(i).getId(), Movie.class); assertEquals(movie.getTitle(), testData.getData().get(i).getTitle()); } } @@ -147,13 +145,13 @@ public void testAddDocumentsInBatches() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task[] taskArr = index.addDocumentsInBatches(testData.getRaw()); + TaskInfo[] taskArr = index.addDocumentsInBatches(testData.getRaw()); - for (Task task : taskArr) { - index.waitForTask(task.getUid()); + for (TaskInfo task : taskArr) { + index.waitForTask(task.getTaskUid()); - assertTrue(task instanceof Task); - assertEquals(task.getType(), "documentAddition"); + assertTrue(task instanceof TaskInfo); + assertEquals("documentAdditionOrUpdate", task.getType()); assertNotNull(task.getEnqueuedAt()); } } @@ -165,13 +163,13 @@ public void testAddDocumentsInBatchesWithBatchSize() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task[] taskArr = index.addDocumentsInBatches(testData.getRaw(), 15, null); + TaskInfo[] taskArr = index.addDocumentsInBatches(testData.getRaw(), 15, null); - for (Task task : taskArr) { - index.waitForTask(task.getUid()); + for (TaskInfo task : taskArr) { + index.waitForTask(task.getTaskUid()); - assertTrue(task instanceof Task); - assertEquals(task.getType(), "documentAddition"); + assertTrue(task instanceof TaskInfo); + assertEquals("documentAdditionOrUpdate", task.getType()); assertNotNull(task.getEnqueuedAt()); } } @@ -184,24 +182,25 @@ public void testUpdateDocument() throws Exception { Index index = createEmptyIndex(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); Movie toUpdate = movies[0]; toUpdate.setTitle("The Perks of Being a Wallflower"); toUpdate.setOverview("The best movie I've ever seen"); task = index.updateDocuments("[" + this.gson.toJson(toUpdate) + "]"); - index.waitForTask(task.getUid()); - Movie responseUpdate = this.gson.fromJson(index.getDocument(toUpdate.getId()), Movie.class); + index.waitForTask(task.getTaskUid()); + Movie responseUpdate = index.getDocument(toUpdate.getId(), Movie.class); assertEquals(toUpdate.getTitle(), responseUpdate.getTitle()); assertEquals(toUpdate.getOverview(), responseUpdate.getOverview()); } - /** Test update Documents with primaryKey */ + /** Test Update Documents with primaryKey */ @Test public void testUpdateDocumentsWithSuppliedPrimaryKey() throws Exception { @@ -220,18 +219,19 @@ public void testUpdateDocumentsWithSuppliedPrimaryKey() throws Exception { secondJson.remove("title"); String secondDocument = this.gson.toJson(secondJson); - Task firstTask = index.updateDocuments("[" + firstDocument + "]", "language"); - index.waitForTask(firstTask.getUid()); + TaskInfo firstTask = index.updateDocuments("[" + firstDocument + "]", "language"); + index.waitForTask(firstTask.getTaskUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); assertEquals(1, movies.length); assertEquals("419704", movies[0].getId()); assertEquals("Ad Astra", movies[0].getTitle()); - Task secondTask = index.updateDocuments("[" + secondDocument + "]", "language"); - index.waitForTask(secondTask.getUid()); + TaskInfo secondTask = index.updateDocuments("[" + secondDocument + "]", "language"); + index.waitForTask(secondTask.getTaskUid()); - movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + movies = (Movie[]) index.getDocuments(Movie.class).getResults(); assertEquals(1, movies.length); assertEquals("574982", movies[0].getId()); // Second movie id assertEquals("Ad Astra", movies[0].getTitle()); // First movie title @@ -244,10 +244,11 @@ public void testUpdateDocuments() throws Exception { Index index = createEmptyIndex(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); List toUpdate = new ArrayList<>(); for (int i = 0; i < 5; i++) { movies[i].setTitle("Star wars episode: " + i); @@ -257,10 +258,9 @@ public void testUpdateDocuments() throws Exception { task = index.updateDocuments(this.gson.toJson(toUpdate)); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); for (int j = 0; j < 5; j++) { - Movie responseUpdate = - this.gson.fromJson(index.getDocument(toUpdate.get(j).getId()), Movie.class); + Movie responseUpdate = index.getDocument(toUpdate.get(j).getId(), Movie.class); assertEquals(toUpdate.get(j).getTitle(), responseUpdate.getTitle()); assertEquals(toUpdate.get(j).getOverview(), responseUpdate.getOverview()); } @@ -274,21 +274,22 @@ public void testUpdateDocumentsInBatchesWithBatchSize() throws Exception { Index index = createEmptyIndex(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task taskIndex = index.addDocuments(testData.getRaw()); + TaskInfo taskIndex = index.addDocuments(testData.getRaw()); - index.waitForTask(taskIndex.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + index.waitForTask(taskIndex.getTaskUid()); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); List toUpdate = new ArrayList<>(); for (int i = 0; i < 5; i++) { movies[i].setTitle("Star wars episode: " + i); movies[i].setOverview("This star wars movie is for the episode: " + i); toUpdate.add(movies[i]); } - Task[] taskArr = index.updateDocumentsInBatches(this.gson.toJson(toUpdate), 2, null); + TaskInfo[] taskArr = index.updateDocumentsInBatches(this.gson.toJson(toUpdate), 2, null); - for (Task task : taskArr) { - index.waitForTask(task.getUid()); - assertEquals(task.getType(), "documentPartial"); + for (TaskInfo task : taskArr) { + index.waitForTask(task.getTaskUid()); + assertEquals(task.getType(), "documentAdditionOrUpdate"); assertNotNull(task.getEnqueuedAt()); } } @@ -301,21 +302,22 @@ public void testUpdateDocumentsInBatches() throws Exception { Index index = createEmptyIndex(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task taskIndex = index.addDocuments(testData.getRaw()); + TaskInfo taskIndex = index.addDocuments(testData.getRaw()); - index.waitForTask(taskIndex.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + index.waitForTask(taskIndex.getTaskUid()); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); List toUpdate = new ArrayList<>(); for (int i = 0; i < 5; i++) { movies[i].setTitle("Star wars episode: " + i); movies[i].setOverview("This star wars movie is for the episode: " + i); toUpdate.add(movies[i]); } - Task[] taskArr = index.updateDocumentsInBatches(this.gson.toJson(toUpdate)); + TaskInfo[] taskArr = index.updateDocumentsInBatches(this.gson.toJson(toUpdate)); - for (Task task : taskArr) { - index.waitForTask(task.getUid()); - assertEquals(task.getType(), "documentPartial"); + for (TaskInfo task : taskArr) { + index.waitForTask(task.getTaskUid()); + assertEquals(task.getType(), "documentAdditionOrUpdate"); assertNotNull(task.getEnqueuedAt()); } } @@ -328,12 +330,27 @@ public void testGetDocument() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); + Movie movie = index.getDocument(testData.getData().get(0).getId(), Movie.class); + assertEquals(movie.getTitle(), testData.getData().get(0).getTitle()); + } + + /** Test default GetRawDocuments */ + @Test + public void testGetRawDocument() throws Exception { + + String indexUid = "GetRawDocument"; + Index index = client.index(indexUid); + + TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); + TaskInfo task = index.addDocuments(testData.getRaw()); + + index.waitForTask(task.getTaskUid()); Movie movie = this.gson.fromJson( - index.getDocument(testData.getData().get(0).getId()), Movie.class); + index.getRawDocument(testData.getData().get(0).getId()), Movie.class); assertEquals(movie.getTitle(), testData.getData().get(0).getTitle()); } @@ -345,15 +362,23 @@ public void testGetDocuments() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); + + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); - index.waitForTask(task.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); assertEquals(20, movies.length); for (int i = 0; i < movies.length; i++) { - Movie movie = - this.gson.fromJson( - index.getDocument(testData.getData().get(i).getId()), Movie.class); + assertEquals(movies[i].getTitle(), testData.getData().get(i).getTitle()); + String[] expectedGenres = testData.getData().get(i).getGenres(); + String[] foundGenres = movies[i].getGenres(); + for (int x = 0; x < expectedGenres.length; x++) { + assertEquals(expectedGenres[x], foundGenres[x]); + } + } + for (int i = 0; i < movies.length; i++) { + Movie movie = index.getDocument(testData.getData().get(i).getId(), Movie.class); assertEquals(movie.getTitle(), testData.getData().get(i).getTitle()); String[] expectedGenres = testData.getData().get(i).getGenres(); String[] foundGenres = movie.getGenres(); @@ -369,18 +394,18 @@ public void testGetDocumentsLimit() throws Exception { String indexUid = "GetDocumentsLimit"; int limit = 24; + DocumentsQuery query = new DocumentsQuery().setLimit(limit); Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(limit), Movie[].class); + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(query, Movie.class); + Movie[] movies = result.getResults(); assertEquals(limit, movies.length); for (int i = 0; i < movies.length; i++) { - Movie movie = - this.gson.fromJson( - index.getDocument(testData.getData().get(i).getId()), Movie.class); + Movie movie = index.getDocument(testData.getData().get(i).getId(), Movie.class); assertEquals(movie.getTitle(), testData.getData().get(i).getTitle()); } } @@ -388,19 +413,22 @@ public void testGetDocumentsLimit() throws Exception { /** Test GetDocuments with limit and offset */ @Test public void testGetDocumentsLimitAndOffset() throws Exception { - String indexUid = "GetDocumentsLimit"; + String indexUid = "GetDocumentsLimitAndOffset"; int limit = 2; int offset = 2; int secondOffset = 5; + DocumentsQuery query = new DocumentsQuery().setLimit(limit).setOffset(offset); Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(limit, offset), Movie[].class); - Movie[] secondMovies = - this.gson.fromJson(index.getDocuments(limit, secondOffset), Movie[].class); + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(query, Movie.class); + Movie[] movies = result.getResults(); + Results secondResults = + index.getDocuments(query.setOffset(secondOffset), Movie.class); + Movie[] secondMovies = secondResults.getResults(); assertEquals(limit, movies.length); assertEquals(limit, secondMovies.length); @@ -409,22 +437,26 @@ public void testGetDocumentsLimitAndOffset() throws Exception { assertNotEquals(movies[1].getTitle(), secondMovies[1].getTitle()); } - /** Test GetDocuments with limit, offset and specified attributesToRetrieve */ + /** Test GetDocuments with limit, offset and specified fields */ @Test - public void testGetDocumentsLimitAndOffsetAndSpecifiedAttributesToRetrieve() throws Exception { - String indexUid = "GetDocumentsLimit"; + public void testGetDocumentsLimitAndOffsetAndSpecifiedFields() throws Exception { + String indexUid = "GetDocumentsLimitAndOffsetAndSpecifiedFields"; int limit = 2; int offset = 2; - List attributesToRetrieve = Arrays.asList("id", "title"); + List fields = Arrays.asList("id", "title"); + DocumentsQuery query = + new DocumentsQuery() + .setLimit(limit) + .setOffset(offset) + .setFields(fields.toArray(new String[0])); Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - Movie[] movies = - this.gson.fromJson( - index.getDocuments(limit, offset, attributesToRetrieve), Movie[].class); + index.waitForTask(task.getTaskUid()); + Results result = index.getDocuments(query, Movie.class); + Movie[] movies = result.getResults(); assertEquals(limit, movies.length); @@ -438,37 +470,97 @@ public void testGetDocumentsLimitAndOffsetAndSpecifiedAttributesToRetrieve() thr assertNull(movies[0].getRelease_date()); } - /** Test GetDocuments with limit, offset and attributesToRetrieve */ - @ParameterizedTest - @MethodSource("attributesToRetrieve") - public void testGetDocumentsLimitAndOffsetAndAttributesToRetrieve( - List attributesToRetrieve) throws Exception { - String indexUid = "GetDocumentsLimit"; + /** Test default GetRawDocuments */ + @Test + public void testGetRawDocuments() throws Exception { + String indexUid = "GetRawDocuments"; + Index index = client.index(indexUid); + + TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); + TaskInfo task = index.addDocuments(testData.getRaw()); + + index.waitForTask(task.getTaskUid()); + String results = index.getRawDocuments(); + + assertTrue(results.contains("results")); + assertTrue(results.contains(testData.getData().get(0).getId())); + assertTrue(results.contains(testData.getData().get(0).getTitle())); + assertTrue(results.contains(testData.getData().get(0).getGenres()[0])); + assertTrue(results.contains(testData.getData().get(0).getLanguage())); + assertTrue(results.contains(testData.getData().get(0).getOverview())); + assertTrue(results.contains(testData.getData().get(0).getPoster())); + assertTrue(results.contains(testData.getData().get(0).getRelease_date())); + } + + /** Test GetRawDocuments with limit */ + @Test + public void testGetRawDocumentsLimit() throws Exception { + + String indexUid = "GetRawDocumentsLimit"; + int limit = 24; + DocumentsQuery query = new DocumentsQuery().setLimit(limit); + Index index = client.index(indexUid); + + TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); + TaskInfo task = index.addDocuments(testData.getRaw()); + + index.waitForTask(task.getTaskUid()); + String results = index.getRawDocuments(query); + + assertTrue(results.contains("results")); + assertTrue(results.contains("\"limit\":24")); + } + + /** Test GetRawDocuments with limit and offset */ + @Test + public void testGetRawDocumentsLimitAndOffset() throws Exception { + String indexUid = "GetRawDocumentsLimitAndOffset"; int limit = 2; int offset = 2; + int secondOffset = 5; + DocumentsQuery query = new DocumentsQuery().setLimit(limit).setOffset(offset); Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - Movie[] movies = - this.gson.fromJson( - index.getDocuments(limit, offset, attributesToRetrieve), Movie[].class); - - assertEquals(limit, movies.length); + index.waitForTask(task.getTaskUid()); + String results = index.getRawDocuments(query); - assertNotNull(movies[0].getId()); - assertNotNull(movies[0].getTitle()); - assertNotNull(movies[0].getGenres()); - assertNotNull(movies[0].getLanguage()); - assertNotNull(movies[0].getOverview()); - assertNotNull(movies[0].getPoster()); - assertNotNull(movies[0].getRelease_date()); + assertTrue(results.contains("results")); + assertTrue(results.contains("\"limit\":2")); + assertTrue(results.contains("\"offset\":2")); } - private static Stream> attributesToRetrieve() { - return Stream.of(emptyList(), null); + /** Test GetRawDocuments with limit, offset and specified fields */ + @Test + public void testGetRawDocumentsLimitAndOffsetAndSpecifiedFields() throws Exception { + String indexUid = "GetRawDocumentsLimitAndOffsetAndSpecifiedFields"; + int limit = 2; + int offset = 2; + List fields = Arrays.asList("id", "title"); + DocumentsQuery query = + new DocumentsQuery() + .setLimit(limit) + .setOffset(offset) + .setFields(fields.toArray(new String[0])); + Index index = client.index(indexUid); + + TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); + TaskInfo task = index.addDocuments(testData.getRaw()); + + index.waitForTask(task.getTaskUid()); + String results = index.getRawDocuments(query); + + assertTrue(results.contains("results")); + assertTrue(results.contains("\"limit\":2")); + assertTrue(results.contains("\"offset\":2")); + assertTrue(results.contains("id")); + assertTrue(results.contains("title")); + assertFalse(results.contains("genres")); + assertFalse(results.contains("langage")); + assertFalse(results.contains("poster")); + assertFalse(results.contains("release_date")); } /** Test deleteDocument */ @@ -479,15 +571,18 @@ public void testDeleteDocument() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + TaskInfo task = index.addDocuments(testData.getRaw()); + index.waitForTask(task.getTaskUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); Movie toDelete = movies[0]; task = index.deleteDocument(toDelete.getId()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); - assertThrows(MeilisearchApiException.class, () -> index.getDocument(toDelete.getId())); + assertThrows( + MeilisearchApiException.class, + () -> index.getDocument(toDelete.getId(), Movie.class)); } /** Test deleteDocuments */ @@ -498,18 +593,19 @@ public void testDeleteDocuments() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + TaskInfo task = index.addDocuments(testData.getRaw()); + index.waitForTask(task.getTaskUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); assertEquals(20, movies.length); List identifiersToDelete = getIdentifiersToDelete(movies); task = index.deleteDocuments(identifiersToDelete); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); - movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + movies = (Movie[]) index.getDocuments(Movie.class).getResults(); boolean containsDeletedMovie = Arrays.stream(movies) @@ -531,20 +627,21 @@ public void testDeleteAllDocuments() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task taskIndex = index.addDocuments(testData.getRaw()); - index.waitForTask(taskIndex.getUid()); + TaskInfo taskIndex = index.addDocuments(testData.getRaw()); + index.waitForTask(taskIndex.getTaskUid()); - Movie[] movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + Results result = index.getDocuments(Movie.class); + Movie[] movies = result.getResults(); assertEquals(20, movies.length); - Task task = index.deleteAllDocuments(); - index.waitForTask(task.getUid()); + TaskInfo task = index.deleteAllDocuments(); + index.waitForTask(task.getTaskUid()); - assertTrue(task instanceof Task); - assertEquals(task.getType(), "clearAll"); + assertTrue(task instanceof TaskInfo); + assertEquals(task.getType(), "documentDeletion"); assertNotNull(task.getEnqueuedAt()); - movies = this.gson.fromJson(index.getDocuments(), Movie[].class); + movies = (Movie[]) index.getDocuments(Movie.class).getResults(); assertEquals(0, movies.length); } } diff --git a/src/test/java/com/meilisearch/integration/InstanceTest.java b/src/test/java/com/meilisearch/integration/InstanceTest.java index 1e557481..b4c84419 100644 --- a/src/test/java/com/meilisearch/integration/InstanceTest.java +++ b/src/test/java/com/meilisearch/integration/InstanceTest.java @@ -6,7 +6,7 @@ import com.meilisearch.sdk.Index; import com.meilisearch.sdk.model.IndexStats; import com.meilisearch.sdk.model.Stats; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; @@ -64,9 +64,9 @@ public void testGetStats() throws Exception { public void testGetIndexStats() throws Exception { String indexUid = "IndexStats"; Index index = client.index(indexUid); - Task task = client.createIndex(indexUid); + TaskInfo task = client.createIndex(indexUid); - client.waitForTask(task.getUid()); + client.waitForTask(task.getTaskUid()); IndexStats stats = index.getStats(); assertNotNull(stats); diff --git a/src/test/java/com/meilisearch/integration/KeysTest.java b/src/test/java/com/meilisearch/integration/KeysTest.java index 1b2fc2c1..a2c3d4b6 100644 --- a/src/test/java/com/meilisearch/integration/KeysTest.java +++ b/src/test/java/com/meilisearch/integration/KeysTest.java @@ -3,8 +3,11 @@ import static org.junit.jupiter.api.Assertions.*; import com.meilisearch.integration.classes.AbstractIT; +import com.meilisearch.sdk.exceptions.MeilisearchApiException; import com.meilisearch.sdk.model.Key; -import com.meilisearch.sdk.model.Result; +import com.meilisearch.sdk.model.KeyUpdate; +import com.meilisearch.sdk.model.KeysQuery; +import com.meilisearch.sdk.model.Results; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.jupiter.api.AfterAll; @@ -19,6 +22,8 @@ public class KeysTest extends AbstractIT { public void initialize() { this.setUp(); this.setUpJacksonClient(); + cleanup(); + deleteAllKeys(); } @AfterAll @@ -30,13 +35,14 @@ static void cleanMeilisearch() { /** Test Get Keys */ @Test public void testClientGetKeys() throws Exception { - Result result = client.getKeys(); + Results result = client.getKeys(); Key[] keys = result.getResults(); assertEquals(2, keys.length); for (Key key : keys) { assertNotNull(key.getKey()); + assertNotNull(key.getUid()); assertNotNull(key.getActions()); assertNotNull(key.getIndexes()); assertNotNull(key.getDescription()); @@ -49,10 +55,10 @@ public void testClientGetKeys() throws Exception { /** Test Get Keys with Jackson Json Handler */ @Test public void testClientGetKeysWithJacksonJsonHandler() throws Exception { - Result result = clientJackson.getKeys(); + Results result = clientJackson.getKeys(); Key[] keys = result.getResults(); - assertEquals(5, keys.length); + assertEquals(2, keys.length); for (Key key : keys) { assertNotNull(key.getKey()); @@ -63,36 +69,104 @@ public void testClientGetKeysWithJacksonJsonHandler() throws Exception { } } + /** Test Get Keys With Limit */ + @Test + public void testClientGetKeysLimit() throws Exception { + int limit = 24; + KeysQuery query = new KeysQuery().setLimit(limit); + + Results result = client.getKeys(query); + + assertEquals(limit, result.getLimit()); + assertNotNull(result.getOffset()); + assertNotNull(result.getTotal()); + assertNotNull(result.getResults().length); + } + + /** Test Get Keys With Limit and Offset */ + @Test + public void testClientGetKeysLimitAndOffset() throws Exception { + int limit = 24; + int offset = 2; + KeysQuery query = new KeysQuery().setLimit(limit).setOffset(offset); + + Results result = client.getKeys(query); + + assertEquals(limit, result.getLimit()); + assertEquals(offset, result.getOffset()); + assertNotNull(result.getTotal()); + assertNotNull(result.getResults().length); + } + /** Test Get Key */ @Test public void testClientGetKey() throws Exception { + Results result = client.getKeys(); + Key[] keys = result.getResults(); + + Key key = client.getKey(keys[0].getKey()); + + assertTrue(key instanceof Key); + assertNotNull(key.getKey()); + assertNotNull(key.getActions()); + assertNotNull(key.getIndexes()); + assertNotNull(key.getDescription()); + assertNotNull(key.getCreatedAt()); + assertNotNull(key.getUpdatedAt()); + } + + /** Test Get Key With Uid */ + @Test + public void testClientGetKeyWithUid() throws Exception { + Results result = client.getKeys(); + Key[] keys = result.getResults(); + + Key key = client.getKey(keys[0].getUid()); + + assertTrue(key instanceof Key); + assertNotNull(key.getKey()); + assertNotNull(key.getActions()); + assertNotNull(key.getIndexes()); + assertNotNull(key.getDescription()); + assertNotNull(key.getCreatedAt()); + assertNotNull(key.getUpdatedAt()); + } + + /** Test Get Key when the key does not exist */ + @Test + public void testClientGetKeyDoesNotExist() throws Exception { + assertThrows(MeilisearchApiException.class, () -> client.getKey("KeyDoesNotExist")); + } + + /** Test Create a simple API Key without description */ + @Test + public void testClientCreateDefaultKey() throws Exception { Key keyInfo = new Key(); keyInfo.setIndexes(new String[] {"*"}); keyInfo.setActions(new String[] {"*"}); keyInfo.setExpiresAt(null); - Key createKey = client.createKey(keyInfo); - Key key = client.getKey(createKey.getKey()); + Key key = client.createKey(keyInfo); assertTrue(key instanceof Key); assertNotNull(key.getKey()); - assertNotNull(key.getActions()); - assertNotNull(key.getIndexes()); + assertEquals("*", key.getActions()[0]); + assertEquals("*", key.getIndexes()[0]); assertNull(key.getDescription()); assertNull(key.getExpiresAt()); assertNotNull(key.getCreatedAt()); assertNotNull(key.getUpdatedAt()); } - /** Test Create a simple API Key without description */ + /** Test Create a simple API Key without description with Jackson Json Handler */ @Test - public void testClientCreateDefaultKey() throws Exception { + public void testClientCreateDefaultKeyWithJacksonJsonHandler() throws Exception { Key keyInfo = new Key(); keyInfo.setIndexes(new String[] {"*"}); keyInfo.setActions(new String[] {"*"}); keyInfo.setExpiresAt(null); - Key key = client.createKey(keyInfo); + Key key = clientJackson.createKey(keyInfo); assertTrue(key instanceof Key); assertNotNull(key.getKey()); @@ -155,13 +229,15 @@ public void testClientUpdateKey() throws Exception { Date dateParsed = format.parse("2042-01-30T00:00:00Z"); Key keyInfo = new Key(); + keyInfo.setName("Key"); + keyInfo.setDescription("Description Key To Update - test"); keyInfo.setIndexes(new String[] {"*"}); - keyInfo.setActions(new String[] {"*"}); + keyInfo.setActions(new String[] {"search"}); + keyInfo.setExpiresAt(dateParsed); - Key keyChanges = new Key(); - keyChanges.setIndexes(new String[] {"testUpdateKey"}); - keyChanges.setActions(new String[] {"search"}); - keyChanges.setExpiresAt(dateParsed); + KeyUpdate keyChanges = new KeyUpdate(); + keyInfo.setName("Key After Update"); + keyInfo.setDescription("Description Key After Update - test"); Key createKey = client.createKey(keyInfo); Key updateKey = client.updateKey(createKey.getKey(), keyChanges); @@ -169,11 +245,46 @@ public void testClientUpdateKey() throws Exception { assertTrue(createKey instanceof Key); assertTrue(updateKey instanceof Key); assertNotNull(updateKey.getKey()); - assertEquals("*", createKey.getActions()[0]); - assertEquals("search", updateKey.getActions()[0]); assertEquals("*", createKey.getIndexes()[0]); - assertEquals("testUpdateKey", updateKey.getIndexes()[0]); - assertNull(createKey.getExpiresAt()); + assertEquals("search", createKey.getActions()[0]); + assertEquals("Key After Update", createKey.getName()); + assertEquals("Description Key After Update - test", updateKey.getDescription()); + assertEquals(createKey.getIndexes()[0], updateKey.getIndexes()[0]); + assertEquals(createKey.getActions()[0], updateKey.getActions()[0]); + assertEquals(dateParsed, updateKey.getExpiresAt()); + assertNotNull(updateKey.getCreatedAt()); + assertNotNull(updateKey.getUpdatedAt()); + } + + /** Test Update an API Key with Jackson Json Handler */ + @Test + public void testClientUpdateKeyWithJacksonJsonHandler() throws Exception { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + Date dateParsed = format.parse("2042-01-30T00:00:00Z"); + + Key keyInfo = new Key(); + keyInfo.setName("Key"); + keyInfo.setDescription("Description Key To Update - test"); + keyInfo.setIndexes(new String[] {"*"}); + keyInfo.setActions(new String[] {"search"}); + keyInfo.setExpiresAt(dateParsed); + + KeyUpdate keyChanges = new KeyUpdate(); + keyInfo.setName("Key After Update"); + keyInfo.setDescription("Description Key After Update - test"); + + Key createKey = clientJackson.createKey(keyInfo); + Key updateKey = clientJackson.updateKey(createKey.getKey(), keyChanges); + + assertTrue(createKey instanceof Key); + assertTrue(updateKey instanceof Key); + assertNotNull(updateKey.getKey()); + assertEquals("*", createKey.getIndexes()[0]); + assertEquals("search", createKey.getActions()[0]); + assertEquals("Key After Update", createKey.getName()); + assertEquals("Description Key After Update - test", updateKey.getDescription()); + assertEquals(createKey.getIndexes()[0], updateKey.getIndexes()[0]); + assertEquals(createKey.getActions()[0], updateKey.getActions()[0]); assertEquals(dateParsed, updateKey.getExpiresAt()); assertNotNull(updateKey.getCreatedAt()); assertNotNull(updateKey.getUpdatedAt()); @@ -192,4 +303,18 @@ public void testClientDeleteKey() throws Exception { assertThrows(Exception.class, () -> client.getKey(createKey.getKey())); } + + /** Test Delete an API Key With Uid */ + @Test + public void testClientDeleteKeyWithUid() throws Exception { + Key keyInfo = new Key(); + keyInfo.setIndexes(new String[] {"*"}); + keyInfo.setActions(new String[] {"*"}); + keyInfo.setExpiresAt(null); + + Key createKey = client.createKey(keyInfo); + client.deleteKey(createKey.getUid()); + + assertThrows(Exception.class, () -> client.getKey(createKey.getUid())); + } } diff --git a/src/test/java/com/meilisearch/integration/SearchNestedTest.java b/src/test/java/com/meilisearch/integration/SearchNestedTest.java index 6042f217..0b9bcccf 100644 --- a/src/test/java/com/meilisearch/integration/SearchNestedTest.java +++ b/src/test/java/com/meilisearch/integration/SearchNestedTest.java @@ -8,7 +8,7 @@ import com.meilisearch.sdk.SearchRequest; import com.meilisearch.sdk.json.GsonJsonHandler; import com.meilisearch.sdk.model.Settings; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; import com.meilisearch.sdk.utils.Movie; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; @@ -24,7 +24,6 @@ final class Results { int offset; int limit; int nbHits; - boolean exhaustiveNbHits; int processingTimeMs; String query; } @@ -44,8 +43,8 @@ public void testBasicSearchInNestedFields() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(NESTED_MOVIES, Movie.class); - Task task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + TaskInfo task = index.addDocuments(testData.getRaw()); + index.waitForTask(task.getTaskUid()); Results searchResultGson = jsonGson.decode(index.rawSearch("An awesome"), Results.class); assertEquals(1, searchResultGson.hits.length); @@ -61,12 +60,12 @@ public void testSearchOnNestedFieldsWithSearchableAttributes() throws Exception String[] newSearchableAttributes = {"title", "info.comment"}; TestData testData = this.getTestData(NESTED_MOVIES, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); index.waitForTask( - index.updateSearchableAttributesSettings(newSearchableAttributes).getUid()); + index.updateSearchableAttributesSettings(newSearchableAttributes).getTaskUid()); Results searchResultGson = jsonGson.decode(index.rawSearch("An awesome"), Results.class); @@ -84,9 +83,9 @@ public void testSearchOnNestedFieldsWithSortableAttributes() throws Exception { newSettings.setSortableAttributes(new String[] {"info.reviewNb"}); TestData testData = this.getTestData(NESTED_MOVIES, Movie.class); - Task task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - index.waitForTask(index.updateSettings(newSettings).getUid()); + TaskInfo task = index.addDocuments(testData.getRaw()); + index.waitForTask(task.getTaskUid()); + index.waitForTask(index.updateSettings(newSettings).getTaskUid()); SearchRequest searchRequest = new SearchRequest("An Awesome").setSort(new String[] {"info.reviewNb:desc"}); @@ -107,9 +106,9 @@ public void testSearchOnNestedFieldsWithSortableAndSearchableAttributes() throws newSettings.setSortableAttributes(new String[] {"info.reviewNb"}); TestData testData = this.getTestData(NESTED_MOVIES, Movie.class); - Task task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); - index.waitForTask(index.updateSettings(newSettings).getUid()); + TaskInfo task = index.addDocuments(testData.getRaw()); + index.waitForTask(task.getTaskUid()); + index.waitForTask(index.updateSettings(newSettings).getTaskUid()); SearchRequest searchRequest = new SearchRequest("An Awesome").setSort(new String[] {"info.reviewNb:desc"}); Results searchResultGson = jsonGson.decode(index.rawSearch(searchRequest), Results.class); diff --git a/src/test/java/com/meilisearch/integration/SearchTest.java b/src/test/java/com/meilisearch/integration/SearchTest.java index bc1cc4fd..6ef50659 100644 --- a/src/test/java/com/meilisearch/integration/SearchTest.java +++ b/src/test/java/com/meilisearch/integration/SearchTest.java @@ -11,7 +11,7 @@ import com.meilisearch.sdk.json.GsonJsonHandler; import com.meilisearch.sdk.model.SearchResult; import com.meilisearch.sdk.model.Settings; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; import com.meilisearch.sdk.utils.Movie; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; @@ -27,8 +27,7 @@ final class Results { Movie[] hits; int offset; int limit; - int nbHits; - boolean exhaustiveNbHits; + int estimatedTotalHits; int processingTimeMs; String query; } @@ -53,17 +52,17 @@ public void testBasicSearch() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchResult searchResult = index.search("batman"); - assertNull(searchResult.getFacetsDistribution()); + assertNull(searchResult.getFacetDistribution()); assertEquals(1, searchResult.getHits().size()); assertEquals(0, searchResult.getOffset()); assertEquals(20, searchResult.getLimit()); - assertEquals(1, searchResult.getNbHits()); + assertEquals(1, searchResult.getEstimatedTotalHits()); } /** Test search offset */ @@ -73,15 +72,15 @@ public void testSearchOffset() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchRequest searchRequest = new SearchRequest("a").setOffset(20); SearchResult searchResult = index.search(searchRequest); assertEquals(10, searchResult.getHits().size()); - assertEquals(30, searchResult.getNbHits()); + assertEquals(30, searchResult.getEstimatedTotalHits()); } /** Test search limit */ @@ -91,15 +90,15 @@ public void testSearchLimit() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchRequest searchRequest = new SearchRequest("a").setLimit(2); SearchResult searchResult = index.search(searchRequest); assertEquals(2, searchResult.getHits().size()); - assertEquals(30, searchResult.getNbHits()); + assertEquals(30, searchResult.getEstimatedTotalHits()); } /** Test search attributesToRetrieve */ @@ -110,9 +109,9 @@ public void testRawSearchAttributesToRetrieve() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchRequest searchRequest = new SearchRequest("a").setAttributesToRetrieve(new String[] {"id", "title"}); @@ -137,9 +136,9 @@ public void testSearchCrop() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchRequest searchRequest = new SearchRequest("and") @@ -161,9 +160,9 @@ public void testSearchCropMarker() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchRequest searchRequest = new SearchRequest("and") @@ -185,9 +184,9 @@ public void testSearchHighlight() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchRequest searchRequest = new SearchRequest("and").setAttributesToHighlight(new String[] {"title"}); @@ -208,9 +207,9 @@ public void testSearchWithCustomizedHighlight() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchRequest searchRequest = new SearchRequest("and") @@ -234,9 +233,9 @@ public void testSearchPhrase() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); Results resGson = jsonGson.decode(index.rawSearch("coco \"harry\""), Results.class); @@ -253,14 +252,14 @@ public void testRawSearchFilter() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); Settings settings = index.getSettings(); settings.setFilterableAttributes(new String[] {"title"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); SearchRequest searchRequest = new SearchRequest("and").setFilter(new String[] {"title = \"The Dark Knight\""}); @@ -280,14 +279,14 @@ public void testRawSearchFilterComplex() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); Settings settings = index.getSettings(); settings.setFilterableAttributes(new String[] {"title", "id"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); SearchRequest searchRequest = new SearchRequest("and") @@ -307,22 +306,21 @@ public void testSearchFacetsDistribution() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); Settings settings = index.getSettings(); settings.setFilterableAttributes(new String[] {"title"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); - SearchRequest searchRequest = - new SearchRequest("knight").setFacetsDistribution(new String[] {"*"}); + SearchRequest searchRequest = new SearchRequest("knight").setFacets(new String[] {"*"}); SearchResult searchResult = index.search(searchRequest); assertEquals(1, searchResult.getHits().size()); - assertNotNull(searchResult.getFacetsDistribution()); + assertNotNull(searchResult.getFacetDistribution()); } /** Test search sort */ @@ -333,14 +331,14 @@ public void testRawSearchSort() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); Settings settings = index.getSettings(); settings.setSortableAttributes(new String[] {"title"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); SearchRequest searchRequest = new SearchRequest("and").setSort(new String[] {"title:asc"}); @@ -363,14 +361,14 @@ public void testRawSearchSortWithIntParameter() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); Settings settings = index.getSettings(); settings.setSortableAttributes(new String[] {"id"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); SearchRequest searchRequest = new SearchRequest("and").setSort(new String[] {"id:asc"}); @@ -393,14 +391,14 @@ public void testRawSearchSortWithMultipleParameter() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); Settings settings = index.getSettings(); settings.setSortableAttributes(new String[] {"id", "title"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); SearchRequest searchRequest = new SearchRequest("dark").setSort(new String[] {"id:asc", "title:asc"}); @@ -422,14 +420,14 @@ public void testRawSearchSortWithPlaceHolder() throws Exception { GsonJsonHandler jsonGson = new GsonJsonHandler(); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); Settings settings = index.getSettings(); settings.setSortableAttributes(new String[] {"id", "title"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); SearchRequest searchRequest = new SearchRequest("").setSort(new String[] {"id:asc", "title:asc"}); @@ -450,11 +448,11 @@ public void testSearchMatches() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); - SearchRequest searchRequest = new SearchRequest("and").setMatches(true); + SearchRequest searchRequest = new SearchRequest("and").setShowMatchesPosition(true); SearchResult searchResult = index.search(searchRequest); assertEquals(20, searchResult.getHits().size()); @@ -466,9 +464,9 @@ public void testPlaceHolder() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchResult result = index.search(""); assertEquals(20, result.getLimit()); @@ -481,9 +479,9 @@ public void testPlaceHolderWithLimit() throws Exception { Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); + TaskInfo task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + index.waitForTask(task.getTaskUid()); SearchResult searchResult = index.search(new SearchRequest(null).setLimit(10)); assertEquals(10, searchResult.getHits().size()); diff --git a/src/test/java/com/meilisearch/integration/SettingsTest.java b/src/test/java/com/meilisearch/integration/SettingsTest.java index b2d3695a..35bd34cf 100644 --- a/src/test/java/com/meilisearch/integration/SettingsTest.java +++ b/src/test/java/com/meilisearch/integration/SettingsTest.java @@ -12,7 +12,7 @@ import com.meilisearch.integration.classes.TestData; import com.meilisearch.sdk.Index; import com.meilisearch.sdk.model.Settings; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; import com.meilisearch.sdk.model.TypoTolerance; import com.meilisearch.sdk.utils.Movie; import java.util.Arrays; @@ -66,7 +66,7 @@ public void testUpdateSettingsRankingRules() throws Exception { "release_date:desc", "rank:desc" }); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); Settings newSettings = index.getSettings(); assertEquals(8, newSettings.getRankingRules().length); } @@ -82,7 +82,7 @@ public void testUpdateSettingsSynonyms() throws Exception { synonyms.put("logan", new String[] {"wolverine"}); settings.setSynonyms(synonyms); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); Settings newSettings = index.getSettings(); @@ -96,7 +96,7 @@ public void testUpdateSettingsSort() throws Exception { Settings settings = index.getSettings(); settings.setSortableAttributes(new String[] {"title", "year"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); Settings newSettings = index.getSettings(); @@ -114,7 +114,7 @@ public void testUpdateSettingsTypoTolerance() throws Exception { typoTolerance.setDisableOnAttributes(new String[] {"title"}); settings.setTypoTolerance(typoTolerance); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); Settings newSettings = index.getSettings(); @@ -130,7 +130,7 @@ public void testUpdateMultipleSettingsInARow() throws Exception { Settings settingsDisplayedAttr = new Settings(); settingsDisplayedAttr.setDisplayedAttributes( new String[] {"title", "overview", "genres", "release_date"}); - index.waitForTask(index.updateSettings(settingsDisplayedAttr).getUid()); + index.waitForTask(index.updateSettings(settingsDisplayedAttr).getTaskUid()); Settings newSettingsDisplayedAttr = index.getSettings(); Settings settingsRankingRules = new Settings(); @@ -145,7 +145,7 @@ public void testUpdateMultipleSettingsInARow() throws Exception { "release_date:desc", "rank:desc" }); - index.waitForTask(index.updateSettings(settingsRankingRules).getUid()); + index.waitForTask(index.updateSettings(settingsRankingRules).getTaskUid()); Settings newSettingsRankingRules = index.getSettings(); Settings settingsSynonyms = new Settings(); @@ -153,7 +153,7 @@ public void testUpdateMultipleSettingsInARow() throws Exception { synonyms.put("wolverine", new String[] {"xmen", "logan"}); synonyms.put("logan", new String[] {"wolverine"}); settingsSynonyms.setSynonyms(synonyms); - index.waitForTask(index.updateSettings(settingsSynonyms).getUid()); + index.waitForTask(index.updateSettings(settingsSynonyms).getTaskUid()); Settings newSettingsSynonyms = index.getSettings(); assertEquals(4, newSettingsDisplayedAttr.getDisplayedAttributes().length); @@ -179,11 +179,11 @@ public void testResetSettings() throws Exception { synonyms.put("logan", new String[] {"wolverine"}); settingsWithSynonyms.setSynonyms(synonyms); - index.waitForTask(index.updateSettings(settingsWithSynonyms).getUid()); + index.waitForTask(index.updateSettings(settingsWithSynonyms).getTaskUid()); settingsWithSynonyms = index.getSettings(); assertEquals(2, settingsWithSynonyms.getSynonyms().size()); - index.waitForTask(index.resetSettings().getUid()); + index.waitForTask(index.resetSettings().getTaskUid()); Settings settingsAfterReset = index.getSettings(); assertEquals(initialSettings.getSynonyms().size(), settingsAfterReset.getSynonyms().size()); } @@ -216,7 +216,7 @@ public void testUpdateRankingRuleSettings() throws Exception { "rank:desc" }; - index.waitForTask(index.updateRankingRuleSettings(newRankingRules).getUid()); + index.waitForTask(index.updateRankingRuleSettings(newRankingRules).getTaskUid()); String[] updatedRankingRuleSettings = index.getRankingRuleSettings(); assertEquals(newRankingRules.length, updatedRankingRuleSettings.length); @@ -240,10 +240,10 @@ public void testResetRankingRuleSettings() throws Exception { "rank:desc" }; - index.waitForTask(index.updateRankingRuleSettings(newRankingRules).getUid()); + index.waitForTask(index.updateRankingRuleSettings(newRankingRules).getTaskUid()); String[] updatedRankingRuleSettings = index.getRankingRuleSettings(); - index.waitForTask(index.resetRankingRuleSettings().getUid()); + index.waitForTask(index.resetRankingRuleSettings().getTaskUid()); String[] rankingRulesAfterReset = index.getRankingRuleSettings(); assertEquals(newRankingRules.length, updatedRankingRuleSettings.length); @@ -277,7 +277,7 @@ public void testUpdateSynonymsSettings() throws Exception { newSynonymsSettings.put("logan", new String[] {"wolverine", "xmen"}); newSynonymsSettings.put("wow", new String[] {"world of warcraft"}); - index.waitForTask(index.updateSynonymsSettings(newSynonymsSettings).getUid()); + index.waitForTask(index.updateSynonymsSettings(newSynonymsSettings).getTaskUid()); Map updatedSynonymsSettings = index.getSynonymsSettings(); assertEquals(newSynonymsSettings.size(), updatedSynonymsSettings.size()); @@ -296,10 +296,10 @@ public void testResetSynonymsSettings() throws Exception { newSynonymsSettings.put("logan", new String[] {"wolverine", "xmen"}); newSynonymsSettings.put("wow", new String[] {"world of warcraft"}); - index.waitForTask(index.updateSynonymsSettings(newSynonymsSettings).getUid()); + index.waitForTask(index.updateSynonymsSettings(newSynonymsSettings).getTaskUid()); Map updatedSynonymsSettings = index.getSynonymsSettings(); - index.waitForTask(index.resetSynonymsSettings().getUid()); + index.waitForTask(index.resetSynonymsSettings().getTaskUid()); Map synonymsSettingsAfterReset = index.getSynonymsSettings(); assertEquals(newSynonymsSettings.size(), updatedSynonymsSettings.size()); @@ -331,7 +331,7 @@ public void testUpdateStopWordsSettings() throws Exception { String[] initialStopWords = index.getStopWordsSettings(); String[] newStopWords = {"of", "the", "to"}; - index.waitForTask(index.updateStopWordsSettings(newStopWords).getUid()); + index.waitForTask(index.updateStopWordsSettings(newStopWords).getTaskUid()); String[] updatedStopWordsSettings = index.getStopWordsSettings(); assertEquals(newStopWords.length, updatedStopWordsSettings.length); @@ -346,10 +346,10 @@ public void testResetStopWordsSettings() throws Exception { String[] initialStopWords = index.getStopWordsSettings(); String[] newStopWords = {"of", "the", "to"}; - index.waitForTask(index.updateStopWordsSettings(newStopWords).getUid()); + index.waitForTask(index.updateStopWordsSettings(newStopWords).getTaskUid()); String[] updatedStopWordsSettings = index.getStopWordsSettings(); - index.waitForTask(index.resetStopWordsSettings().getUid()); + index.waitForTask(index.resetStopWordsSettings().getTaskUid()); String[] stopWordsAfterReset = index.getStopWordsSettings(); assertEquals(newStopWords.length, updatedStopWordsSettings.length); @@ -383,7 +383,7 @@ public void testUpdateSearchableAttributesSettings() throws Exception { String[] newSearchableAttributes = {"title", "description", "genre"}; index.waitForTask( - index.updateSearchableAttributesSettings(newSearchableAttributes).getUid()); + index.updateSearchableAttributesSettings(newSearchableAttributes).getTaskUid()); String[] updatedSearchableAttributes = index.getSearchableAttributesSettings(); assertEquals(newSearchableAttributes.length, updatedSearchableAttributes.length); @@ -399,10 +399,10 @@ public void testResetSearchableAttributesSettings() throws Exception { String[] newSearchableAttributes = {"title", "description", "genre"}; index.waitForTask( - index.updateSearchableAttributesSettings(newSearchableAttributes).getUid()); + index.updateSearchableAttributesSettings(newSearchableAttributes).getTaskUid()); String[] updatedSearchableAttributes = index.getSearchableAttributesSettings(); - index.waitForTask(index.resetSearchableAttributesSettings().getUid()); + index.waitForTask(index.resetSearchableAttributesSettings().getTaskUid()); String[] searchableAttributesAfterReset = index.getSearchableAttributesSettings(); assertEquals(newSearchableAttributes.length, updatedSearchableAttributes.length); @@ -435,7 +435,8 @@ public void testUpdateDisplayedAttributesSettings() throws Exception { String[] initialDisplayedAttributes = index.getDisplayedAttributesSettings(); String[] newDisplayedAttributes = {"title", "description", "genre", "release_date"}; - index.waitForTask(index.updateDisplayedAttributesSettings(newDisplayedAttributes).getUid()); + index.waitForTask( + index.updateDisplayedAttributesSettings(newDisplayedAttributes).getTaskUid()); String[] updatedDisplayedAttributes = index.getDisplayedAttributesSettings(); assertEquals(newDisplayedAttributes.length, updatedDisplayedAttributes.length); @@ -450,10 +451,11 @@ public void testResetDisplayedAttributesSettings() throws Exception { String[] initialDisplayedAttributes = index.getDisplayedAttributesSettings(); String[] newDisplayedAttributes = {"title", "description", "genre", "release_date", "cast"}; - index.waitForTask(index.updateDisplayedAttributesSettings(newDisplayedAttributes).getUid()); + index.waitForTask( + index.updateDisplayedAttributesSettings(newDisplayedAttributes).getTaskUid()); String[] updatedDisplayedAttributes = index.getDisplayedAttributesSettings(); - index.waitForTask(index.resetDisplayedAttributesSettings().getUid()); + index.waitForTask(index.resetDisplayedAttributesSettings().getTaskUid()); String[] displayedAttributesAfterReset = index.getDisplayedAttributesSettings(); assertEquals(newDisplayedAttributes.length, updatedDisplayedAttributes.length); @@ -485,7 +487,7 @@ public void testUpdateFilterableAttributesSettings() throws Exception { String[] newFilterableAttributes = {"title", "description", "genre", "release_date"}; index.waitForTask( - index.updateFilterableAttributesSettings(newFilterableAttributes).getUid()); + index.updateFilterableAttributesSettings(newFilterableAttributes).getTaskUid()); String[] updatedFilterableAttributes = index.getFilterableAttributesSettings(); assertEquals(newFilterableAttributes.length, updatedFilterableAttributes.length); @@ -505,10 +507,10 @@ public void testResetFilterableAttributesSettings() throws Exception { }; index.waitForTask( - index.updateFilterableAttributesSettings(newFilterableAttributes).getUid()); + index.updateFilterableAttributesSettings(newFilterableAttributes).getTaskUid()); String[] updatedFilterableAttributes = index.getFilterableAttributesSettings(); - index.waitForTask(index.resetFilterableAttributesSettings().getUid()); + index.waitForTask(index.resetFilterableAttributesSettings().getTaskUid()); String[] filterableAttributesAfterReset = index.getFilterableAttributesSettings(); assertEquals(newFilterableAttributes.length, updatedFilterableAttributes.length); @@ -539,7 +541,7 @@ public void testUpdateDistinctAttributeSettings() throws Exception { String initialDistinctAttribute = index.getDistinctAttributeSettings(); String newDistinctAttribute = "title"; - index.waitForTask(index.updateDistinctAttributeSettings(newDistinctAttribute).getUid()); + index.waitForTask(index.updateDistinctAttributeSettings(newDistinctAttribute).getTaskUid()); String updatedDistinctAttribute = index.getDistinctAttributeSettings(); assertEquals(newDistinctAttribute, updatedDistinctAttribute); @@ -553,10 +555,10 @@ public void testResetDistinctAttributeSettings() throws Exception { String initialDistinctAttribute = index.getDistinctAttributeSettings(); String newDistinctAttribute = "title"; - index.waitForTask(index.updateDistinctAttributeSettings(newDistinctAttribute).getUid()); + index.waitForTask(index.updateDistinctAttributeSettings(newDistinctAttribute).getTaskUid()); String updatedDistinctAttribute = index.getDistinctAttributeSettings(); - index.waitForTask(index.resetDistinctAttributeSettings().getUid()); + index.waitForTask(index.resetDistinctAttributeSettings().getTaskUid()); String distinctAttributeAfterReset = index.getDistinctAttributeSettings(); assertEquals(newDistinctAttribute, updatedDistinctAttribute); @@ -603,7 +605,7 @@ public void testUpdateTypoTolerance() throws Exception { } }; newTypoTolerance.setMinWordSizeForTypos(minWordSizeTypos); - index.waitForTask(index.updateTypoToleranceSettings(newTypoTolerance).getUid()); + index.waitForTask(index.updateTypoToleranceSettings(newTypoTolerance).getTaskUid()); TypoTolerance updatedTypoTolerance = index.getTypoToleranceSettings(); assertEquals( @@ -629,7 +631,7 @@ public void testPartialUpdateTypoTolerance() throws Exception { newTypoTolerance.setDisableOnWords(new String[] {"the"}); newTypoTolerance.setDisableOnAttributes(new String[] {"title"}); - index.waitForTask(index.updateTypoToleranceSettings(newTypoTolerance).getUid()); + index.waitForTask(index.updateTypoToleranceSettings(newTypoTolerance).getTaskUid()); TypoTolerance updatedTypoTolerance = index.getTypoToleranceSettings(); assertEquals( @@ -666,10 +668,10 @@ public void testResetTypoTolerance() throws Exception { }; newTypoTolerance.setMinWordSizeForTypos(minWordSizeTypos); - index.waitForTask(index.updateTypoToleranceSettings(newTypoTolerance).getUid()); + index.waitForTask(index.updateTypoToleranceSettings(newTypoTolerance).getTaskUid()); TypoTolerance updatedTypoTolerance = index.getTypoToleranceSettings(); - index.waitForTask(index.resetTypoToleranceSettings().getUid()); + index.waitForTask(index.resetTypoToleranceSettings().getTaskUid()); TypoTolerance typoToleranceAfterReset = index.getTypoToleranceSettings(); assertEquals( @@ -706,10 +708,10 @@ public void testUpdateSynonymsSettingsUsingNull() throws Exception { newSynonymsSettings.put("007", new String[] {"james bond", "bond"}); newSynonymsSettings.put("ironman", new String[] {"tony stark", "iron man"}); - index.waitForTask(index.updateSynonymsSettings(newSynonymsSettings).getUid()); + index.waitForTask(index.updateSynonymsSettings(newSynonymsSettings).getTaskUid()); Map updatedSynonymsSettings = index.getSynonymsSettings(); - index.waitForTask(index.updateSynonymsSettings(null).getUid()); + index.waitForTask(index.updateSynonymsSettings(null).getTaskUid()); Map resetSynonymsSettings = index.getSynonymsSettings(); assertNotEquals(initialSynonymsSettings.size(), updatedSynonymsSettings.size()); @@ -725,10 +727,10 @@ public void testUpdateStopWordsSettingsUsingNull() throws Exception { String[] initialStopWords = index.getStopWordsSettings(); String[] newStopWords = {"the", "to", "in", "on"}; - index.waitForTask(index.updateStopWordsSettings(newStopWords).getUid()); + index.waitForTask(index.updateStopWordsSettings(newStopWords).getTaskUid()); String[] updatedStopWords = index.getStopWordsSettings(); - index.waitForTask(index.updateStopWordsSettings(null).getUid()); + index.waitForTask(index.updateStopWordsSettings(null).getTaskUid()); String[] resetStopWords = index.getStopWordsSettings(); assertNotEquals(initialStopWords.length, updatedStopWords.length); @@ -753,10 +755,10 @@ public void testUpdateRankingRuleSettingsUsingNull() throws Exception { "rank:desc" }; - index.waitForTask(index.updateRankingRuleSettings(newRankingRules).getUid()); + index.waitForTask(index.updateRankingRuleSettings(newRankingRules).getTaskUid()); String[] newRankingRule = index.getRankingRuleSettings(); - index.waitForTask(index.updateRankingRuleSettings(null).getUid()); + index.waitForTask(index.updateRankingRuleSettings(null).getTaskUid()); String[] resetRankingRule = index.getRankingRuleSettings(); assertNotEquals(newRankingRule.length, resetRankingRule.length); @@ -772,10 +774,10 @@ public void testUpdateSearchableAttributesSettingssUsingNull() throws Exception String[] newSearchableAttributes = {"title", "release_date", "cast"}; index.waitForTask( - index.updateSearchableAttributesSettings(newSearchableAttributes).getUid()); + index.updateSearchableAttributesSettings(newSearchableAttributes).getTaskUid()); String[] updatedSearchableAttributes = index.getSearchableAttributesSettings(); - index.waitForTask(index.updateSearchableAttributesSettings(null).getUid()); + index.waitForTask(index.updateSearchableAttributesSettings(null).getTaskUid()); String[] resetSearchableAttributes = index.getSearchableAttributesSettings(); assertNotEquals(initialSearchableAttributes.length, updatedSearchableAttributes.length); @@ -791,10 +793,11 @@ public void testUpdateDisplayedAttributesSettingsUsingNull() throws Exception { String[] initialDisplayedAttributes = index.getDisplayedAttributesSettings(); String[] newDisplayedAttributes = {"title", "genre", "release_date"}; - index.waitForTask(index.updateDisplayedAttributesSettings(newDisplayedAttributes).getUid()); + index.waitForTask( + index.updateDisplayedAttributesSettings(newDisplayedAttributes).getTaskUid()); String[] updatedDisplayedAttributes = index.getDisplayedAttributesSettings(); - index.waitForTask(index.updateDisplayedAttributesSettings(null).getUid()); + index.waitForTask(index.updateDisplayedAttributesSettings(null).getTaskUid()); String[] resetDisplayedAttributes = index.getDisplayedAttributesSettings(); assertNotEquals(initialDisplayedAttributes.length, updatedDisplayedAttributes.length); @@ -811,10 +814,10 @@ public void testUpdateFilterableAttributesSettingsUsingNull() throws Exception { String[] newFilterableAttributes = {"title", "genres", "cast", "release_date"}; index.waitForTask( - index.updateFilterableAttributesSettings(newFilterableAttributes).getUid()); + index.updateFilterableAttributesSettings(newFilterableAttributes).getTaskUid()); String[] updatedFilterableAttributes = index.getFilterableAttributesSettings(); - index.waitForTask(index.updateFilterableAttributesSettings(null).getUid()); + index.waitForTask(index.updateFilterableAttributesSettings(null).getTaskUid()); String[] resetFilterableAttributes = index.getFilterableAttributesSettings(); assertNotEquals(updatedFilterableAttributes.length, resetFilterableAttributes.length); @@ -830,10 +833,10 @@ public void testUpdateDistinctAttributeSettingsUsingNull() throws Exception { String initialDistinctAttribute = index.getDistinctAttributeSettings(); String newDistinctAttribute = "genres"; - index.waitForTask(index.updateDistinctAttributeSettings(newDistinctAttribute).getUid()); + index.waitForTask(index.updateDistinctAttributeSettings(newDistinctAttribute).getTaskUid()); String updatedDistinctAttribute = index.getDistinctAttributeSettings(); - index.waitForTask(index.updateDistinctAttributeSettings(null).getUid()); + index.waitForTask(index.updateDistinctAttributeSettings(null).getTaskUid()); String resetDistinctAttribute = index.getDistinctAttributeSettings(); assertNotEquals(updatedDistinctAttribute, resetDistinctAttribute); @@ -843,8 +846,8 @@ public void testUpdateDistinctAttributeSettingsUsingNull() throws Exception { private Index createIndex(String indexUid) throws Exception { Index index = client.index(indexUid); - Task updateInfo = index.addDocuments(testData.getRaw()); - index.waitForTask(updateInfo.getUid()); + TaskInfo updateInfo = index.addDocuments(testData.getRaw()); + index.waitForTask(updateInfo.getTaskUid()); return index; } diff --git a/src/test/java/com/meilisearch/integration/TasksTest.java b/src/test/java/com/meilisearch/integration/TasksTest.java index f513af38..829a14f8 100644 --- a/src/test/java/com/meilisearch/integration/TasksTest.java +++ b/src/test/java/com/meilisearch/integration/TasksTest.java @@ -5,8 +5,10 @@ import com.meilisearch.integration.classes.AbstractIT; import com.meilisearch.integration.classes.TestData; import com.meilisearch.sdk.Index; -import com.meilisearch.sdk.model.Result; import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; +import com.meilisearch.sdk.model.TasksQuery; +import com.meilisearch.sdk.model.TasksResults; import com.meilisearch.sdk.utils.Movie; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; @@ -33,10 +35,10 @@ static void cleanMeilisearch() { @Test public void testClientGetTask() throws Exception { String indexUid = "GetClientTask"; - Task response = client.createIndex(indexUid); - client.waitForTask(response.getUid()); + TaskInfo response = client.createIndex(indexUid); + client.waitForTask(response.getTaskUid()); - Task task = client.getTask(response.getUid()); + Task task = client.getTask(response.getTaskUid()); assertTrue(task instanceof Task); assertNotNull(task.getStatus()); @@ -52,7 +54,7 @@ public void testClientGetTask() throws Exception { /** Test Get Tasks */ @Test public void testClientGetTasks() throws Exception { - Result result = client.getTasks(); + TasksResults result = client.getTasks(); Task[] tasks = result.getResults(); for (Task task : tasks) { @@ -68,14 +70,61 @@ public void testClientGetTasks() throws Exception { } } + /** Test Get Tasks with limit */ + @Test + public void testClientGetTasksLimit() throws Exception { + int limit = 2; + TasksQuery query = new TasksQuery().setLimit(limit); + TasksResults result = client.getTasks(query); + + assertEquals(limit, result.getLimit()); + assertNotNull(result.getFrom()); + assertNotNull(result.getNext()); + assertNotNull(result.getResults().length); + } + + /** Test Get Tasks with limit and from */ + @Test + public void testClientGetTasksLimitAndFrom() throws Exception { + int limit = 2; + int from = 2; + TasksQuery query = new TasksQuery().setLimit(limit).setFrom(from); + TasksResults result = client.getTasks(query); + + assertEquals(limit, result.getLimit()); + assertEquals(from, result.getFrom()); + assertNotNull(result.getFrom()); + assertNotNull(result.getNext()); + assertNotNull(result.getResults().length); + } + + /** Test Get Tasks with all query parameters */ + @Test + public void testClientGetTasksAllQueryParameters() throws Exception { + int limit = 2; + int from = 2; + TasksQuery query = + new TasksQuery() + .setLimit(limit) + .setFrom(from) + .setStatus(new String[] {"enqueued", "succeeded"}) + .setType(new String[] {"indexDeletion"}); + TasksResults result = client.getTasks(query); + Task[] tasks = result.getResults(); + + assertEquals(limit, result.getLimit()); + assertNotNull(result.getFrom()); + assertNotNull(result.getNext()); + } + /** Test waitForTask */ @Test public void testWaitForTask() throws Exception { String indexUid = "WaitForTask"; - Task response = client.createIndex(indexUid); - client.waitForTask(response.getUid()); + TaskInfo response = client.createIndex(indexUid); + client.waitForTask(response.getTaskUid()); - Task task = client.getTask(response.getUid()); + Task task = client.getTask(response.getTaskUid()); assertTrue(task.getUid() >= 0); assertNotNull(task.getEnqueuedAt()); @@ -94,9 +143,9 @@ public void testWaitForTaskTimoutInMs() throws Exception { String indexUid = "WaitForTaskTimoutInMs"; Index index = client.index(indexUid); - Task task = index.addDocuments(this.testData.getRaw()); - index.waitForTask(task.getUid()); + TaskInfo task = index.addDocuments(this.testData.getRaw()); + index.waitForTask(task.getTaskUid()); - assertThrows(Exception.class, () -> index.waitForTask(task.getUid(), 0, 50)); + assertThrows(Exception.class, () -> index.waitForTask(task.getTaskUid(), 0, 50)); } } diff --git a/src/test/java/com/meilisearch/integration/TenantTokenTest.java b/src/test/java/com/meilisearch/integration/TenantTokenTest.java index 2a9d0d2b..9eed4929 100644 --- a/src/test/java/com/meilisearch/integration/TenantTokenTest.java +++ b/src/test/java/com/meilisearch/integration/TenantTokenTest.java @@ -12,7 +12,7 @@ import com.meilisearch.sdk.model.Key; import com.meilisearch.sdk.model.SearchResult; import com.meilisearch.sdk.model.Settings; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.TaskInfo; import com.meilisearch.sdk.utils.Movie; import java.util.Date; import java.util.HashMap; @@ -48,7 +48,7 @@ public void testGenerateTenantTokenWithOnlySearchRules() throws Exception { Map rules = new HashMap(); rules.put("*", new HashMap()); - String jwtToken = privateClient.generateTenantToken(rules); + String jwtToken = privateClient.generateTenantToken(getPrivateKey().getUid(), rules); Client tokenClient = new Client(new Config(getMeilisearchHost(), jwtToken)); @@ -67,7 +67,7 @@ public void testGenerateTenantTokenOnOneIndex() throws Exception { Map rules = new HashMap(); rules.put(indexUid, new HashMap()); - String jwtToken = privateClient.generateTenantToken(rules); + String jwtToken = privateClient.generateTenantToken(getPrivateKey().getUid(), rules); Client tokenClient = new Client(new Config(getMeilisearchHost(), jwtToken)); @@ -87,24 +87,24 @@ public void testGenerateTenantTokenWithFilter() throws Exception { Map rules = new HashMap(); rules.put("GenerateTokenwithFilter", filters); - String jwtToken = privateClient.generateTenantToken(rules); + String jwtToken = privateClient.generateTenantToken(getPrivateKey().getUid(), rules); Client tokenClient = new Client(new Config(getMeilisearchHost(), jwtToken)); Index index = client.index(indexUid); TestData testData = this.getTestData(MOVIES_INDEX, Movie.class); - Task task = index.addDocuments(testData.getRaw()); - index.waitForTask(task.getUid()); + TaskInfo task = index.addDocuments(testData.getRaw()); + index.waitForTask(task.getTaskUid()); Settings settings = index.getSettings(); settings.setFilterableAttributes(new String[] {"id"}); - index.waitForTask(index.updateSettings(settings).getUid()); + index.waitForTask(index.updateSettings(settings).getTaskUid()); SearchResult searchResult = tokenClient.index(indexUid).search(""); assertEquals(20, searchResult.getHits().size()); assertEquals(20, searchResult.getLimit()); - assertEquals(30, searchResult.getNbHits()); + assertEquals(30, searchResult.getEstimatedTotalHits()); } /** Test Create Tenant Token with expiration date */ @@ -125,7 +125,8 @@ public void testGenerateTenantTokenWithExpiresAt() throws Exception { TenantTokenOptions options = new TenantTokenOptions(); options.setExpiresAt(tomorrow); - String jwtToken = privateClient.generateTenantToken(rules, options); + String jwtToken = + privateClient.generateTenantToken(getPrivateKey().getUid(), rules, options); Client tokenClient = new Client(new Config(getMeilisearchHost(), jwtToken)); @@ -145,7 +146,7 @@ public void testGenerateTenantTokenWithApiKey() throws Exception { TenantTokenOptions options = new TenantTokenOptions(); options.setApiKey(key.getKey()); - String jwtToken = client.generateTenantToken(rules, options); + String jwtToken = client.generateTenantToken(getPrivateKey().getUid(), rules, options); Client tokenClient = new Client(new Config(getMeilisearchHost(), jwtToken)); @@ -169,7 +170,7 @@ public void testGenerateTenantTokenWithAllOptions() throws Exception { options.setApiKey(key.getKey()); options.setExpiresAt(tomorrow); - String jwtToken = client.generateTenantToken(rules, options); + String jwtToken = client.generateTenantToken(getPrivateKey().getUid(), rules, options); Client tokenClient = new Client(new Config(getMeilisearchHost(), jwtToken)); @@ -183,7 +184,23 @@ public void testGenerateTenantTokenWithNoSearchRules() throws Exception { Client privateClient = new Client(new Config(getMeilisearchHost(), key.getKey())); - assertThrows(MeilisearchException.class, () -> privateClient.generateTenantToken(null)); + assertThrows( + MeilisearchException.class, + () -> privateClient.generateTenantToken(getPrivateKey().getUid(), null)); + } + + /** Test Create Tenant Token with no api key uid */ + @Test + public void testGenerateTenantTokenWithNoApiKeyUid() throws Exception { + Key key = getPrivateKey(); + + Client privateClient = new Client(new Config(getMeilisearchHost(), key.getKey())); + + Map rules = new HashMap(); + rules.put("*", new HashMap()); + + assertThrows( + MeilisearchException.class, () -> privateClient.generateTenantToken(null, rules)); } /** Test Create Tenant Token with bad expireation date */ @@ -205,7 +222,7 @@ public void testGenerateTenantTokenWithBadExpiresAt() throws Exception { assertThrows( MeilisearchException.class, - () -> privateClient.generateTenantToken(rules, options)); + () -> privateClient.generateTenantToken(getPrivateKey().getUid(), rules, options)); } /** Test Create Tenant Token with empty api key */ @@ -220,6 +237,6 @@ public void testGenerateTenantTokenWithEmptyApiKey() throws Exception { assertThrows( MeilisearchException.class, - () -> privateClient.generateTenantToken(rules, options)); + () -> privateClient.generateTenantToken(getPrivateKey().getUid(), rules, options)); } } diff --git a/src/test/java/com/meilisearch/integration/classes/AbstractIT.java b/src/test/java/com/meilisearch/integration/classes/AbstractIT.java index 5d039def..bf156b58 100644 --- a/src/test/java/com/meilisearch/integration/classes/AbstractIT.java +++ b/src/test/java/com/meilisearch/integration/classes/AbstractIT.java @@ -7,8 +7,8 @@ import com.meilisearch.sdk.Index; import com.meilisearch.sdk.json.JacksonJsonHandler; import com.meilisearch.sdk.model.Key; -import com.meilisearch.sdk.model.Result; -import com.meilisearch.sdk.model.Task; +import com.meilisearch.sdk.model.Results; +import com.meilisearch.sdk.model.TaskInfo; import com.meilisearch.sdk.utils.Movie; import java.io.*; import java.net.URL; @@ -59,14 +59,14 @@ public static String getMeilisearchHost() { } public Index createEmptyIndex(String indexUid) throws Exception { - Task task = client.createIndex(indexUid); - client.waitForTask(task.getUid()); + TaskInfo task = client.createIndex(indexUid); + client.waitForTask(task.getTaskUid()); return client.getIndex(indexUid); } public Index createEmptyIndex(String indexUid, String primaryKey) throws Exception { - Task task = client.createIndex(indexUid, primaryKey); - client.waitForTask(task.getUid()); + TaskInfo task = client.createIndex(indexUid, primaryKey); + client.waitForTask(task.getTaskUid()); return client.getIndex(indexUid); } @@ -89,11 +89,10 @@ public void loadResource(String fileName) throws IOException { } public Key getPrivateKey() throws Exception { - Result result = client.getKeys(); + Results result = client.getKeys(); Key[] keys = result.getResults(); for (Key key : keys) { - if ((key.getDescription() == null) - || (key.getDescription().contains("Default Admin API"))) { + if ((key.getName() == null) || (key.getName().contains("Default Admin API"))) { return key; } } @@ -103,9 +102,10 @@ public Key getPrivateKey() throws Exception { public static void deleteAllIndexes() { try { Client ms = new Client(new Config(getMeilisearchHost(), "masterKey")); - Index[] indexes = ms.getIndexes(); - for (Index index : indexes) { - ms.deleteIndex(index.getUid()); + Results indexes = ms.getIndexes(); + for (Index index : indexes.getResults()) { + TaskInfo task = ms.deleteIndex(index.getUid()); + ms.waitForTask(task.getTaskUid()); } } catch (Exception e) { e.printStackTrace(); @@ -115,7 +115,7 @@ public static void deleteAllIndexes() { public static void deleteAllKeys() { try { Client ms = new Client(new Config(getMeilisearchHost(), "masterKey")); - Result result = ms.getKeys(); + Results result = ms.getKeys(); Key[] keys = result.getResults(); for (Key key : keys) { if ((key.getDescription() == null) || (key.getDescription().contains("test"))) { diff --git a/src/test/java/com/meilisearch/sdk/SearchRequestTest.java b/src/test/java/com/meilisearch/sdk/SearchRequestTest.java index e35d0f72..fd741fa2 100644 --- a/src/test/java/com/meilisearch/sdk/SearchRequestTest.java +++ b/src/test/java/com/meilisearch/sdk/SearchRequestTest.java @@ -11,7 +11,7 @@ void toStringSimpleQuery() { SearchRequest classToTest = new SearchRequest("This is a Test"); assertEquals( - "{\"q\":\"This is a Test\",\"attributesToRetrieve\":[\"*\"],\"offset\":0,\"limit\":20,\"cropLength\":200,\"matches\":false}", + "{\"q\":\"This is a Test\",\"attributesToRetrieve\":[\"*\"],\"offset\":0,\"showMatchesPosition\":false,\"limit\":20,\"cropLength\":200}", classToTest.toString()); } @@ -20,7 +20,7 @@ void toStringQueryAndOffset() { SearchRequest classToTest = new SearchRequest("This is a Test", 200); assertEquals( - "{\"q\":\"This is a Test\",\"attributesToRetrieve\":[\"*\"],\"offset\":200,\"limit\":20,\"cropLength\":200,\"matches\":false}", + "{\"q\":\"This is a Test\",\"attributesToRetrieve\":[\"*\"],\"offset\":200,\"showMatchesPosition\":false,\"limit\":20,\"cropLength\":200}", classToTest.toString()); } @@ -29,7 +29,7 @@ void toStringQueryLimitAndOffset() { SearchRequest classToTest = new SearchRequest("This is a Test", 200, 900); assertEquals( - "{\"q\":\"This is a Test\",\"attributesToRetrieve\":[\"*\"],\"offset\":200,\"limit\":900,\"cropLength\":200,\"matches\":false}", + "{\"q\":\"This is a Test\",\"attributesToRetrieve\":[\"*\"],\"offset\":200,\"showMatchesPosition\":false,\"limit\":900,\"cropLength\":200}", classToTest.toString()); } @@ -39,7 +39,7 @@ void toStringQueryLimitOffsetAndAttributesToRetrieve() { new SearchRequest("This is a Test", 200, 900, new String[] {"bubble"}); assertEquals( - "{\"q\":\"This is a Test\",\"attributesToRetrieve\":[\"bubble\"],\"offset\":200,\"limit\":900,\"cropLength\":200,\"matches\":false}", + "{\"q\":\"This is a Test\",\"attributesToRetrieve\":[\"bubble\"],\"offset\":200,\"showMatchesPosition\":false,\"limit\":900,\"cropLength\":200}", classToTest.toString()); } @@ -74,7 +74,7 @@ void toStringEveryParameters() { assertEquals(null, classToTest.getFilterArray()); assertEquals(1, classToTest.getFilter().length); assertEquals("test='test'", classToTest.getFilter()[0]); - assertEquals("facets", classToTest.getFacetsDistribution()[0]); + assertEquals("facets", classToTest.getFacets()[0]); assertEquals("sort", classToTest.getSort()[0]); assertEquals(900, classToTest.getCropLength()); } @@ -113,11 +113,11 @@ void toStringEveryParametersWithArray() { assertEquals(2, classToTest.getFilterArray().length); assertEquals("test='test'", classToTest.getFilterArray()[0][0]); assertEquals("test1='test1'", classToTest.getFilterArray()[1][0]); - assertEquals("facets", classToTest.getFacetsDistribution()[0]); + assertEquals("facets", classToTest.getFacets()[0]); assertEquals("sort", classToTest.getSort()[0]); assertEquals(900, classToTest.getCropLength()); assertEquals( - "{\"attributesToRetrieve\":[\"bubble\"],\"offset\":200,\"cropMarker\":\"123\",\"facetsDistribution\":[\"facets\"],\"sort\":[\"sort\"],\"highlightPreTag\":\"abc\",\"matches\":true,\"filter\":[[\"test='test'\"],[\"test1='test1'\"]],\"q\":\"This is a Test\",\"limit\":900,\"cropLength\":900,\"highlightPostTag\":\"zyx\",\"attributesToHighlight\":[\"highlight\"],\"attributesToCrop\":[\"crop\"]}", + "{\"attributesToRetrieve\":[\"bubble\"],\"offset\":200,\"cropMarker\":\"123\",\"sort\":[\"sort\"],\"highlightPreTag\":\"abc\",\"facets\":[\"facets\"],\"filter\":[[\"test='test'\"],[\"test1='test1'\"]],\"q\":\"This is a Test\",\"showMatchesPosition\":true,\"limit\":900,\"cropLength\":900,\"highlightPostTag\":\"zyx\",\"attributesToHighlight\":[\"highlight\"],\"attributesToCrop\":[\"crop\"]}", classToTest.toString()); } } diff --git a/src/test/java/com/meilisearch/sdk/http/URLBuilderTest.java b/src/test/java/com/meilisearch/sdk/http/URLBuilderTest.java new file mode 100644 index 00000000..7d352c68 --- /dev/null +++ b/src/test/java/com/meilisearch/sdk/http/URLBuilderTest.java @@ -0,0 +1,76 @@ +package com.meilisearch.sdk.http; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +public class URLBuilderTest { + + private final URLBuilder classToTest = new URLBuilder(); + + @Test + void addSubroute() { + classToTest.addSubroute("route"); + + assertEquals("/route", classToTest.getRoutes().toString()); + } + + @Test + void addSubrouteWithMultipleRoutes() { + classToTest + .addSubroute("route1") + .addSubroute("route2") + .addSubroute("route3") + .addSubroute("route4"); + + assertEquals("/route1/route2/route3/route4", classToTest.getRoutes().toString()); + } + + @Test + void addParameterStringInt() { + classToTest.addParameter("parameter1", 1); + assertEquals("?parameter1=1", classToTest.getParams().toString()); + + classToTest.addParameter("parameter2", 2); + assertEquals("?parameter1=1¶meter2=2", classToTest.getParams().toString()); + + classToTest.addParameter("parameter3", 3); + assertEquals("?parameter1=1¶meter2=2¶meter3=3", classToTest.getParams().toString()); + } + + @Test + void addParameterStringString() { + classToTest.addParameter("parameter1", "1"); + assertEquals("?parameter1=1", classToTest.getParams().toString()); + + classToTest.addParameter("parameter2", "2"); + assertEquals("?parameter1=1¶meter2=2", classToTest.getParams().toString()); + + classToTest.addParameter("parameter3", "3"); + assertEquals("?parameter1=1¶meter2=2¶meter3=3", classToTest.getParams().toString()); + } + + @Test + void addParameterStringArray() { + classToTest.addParameter("parameter1", new String[] {"1", "a"}); + assertEquals("?parameter1=1,a", classToTest.getParams().toString()); + + classToTest.addParameter("parameter2", new String[] {"2", "b"}); + assertEquals("?parameter1=1,a¶meter2=2,b", classToTest.getParams().toString()); + + classToTest.addParameter("parameter3", new String[] {"3", "c"}); + assertEquals( + "?parameter1=1,a¶meter2=2,b¶meter3=3,c", + classToTest.getParams().toString()); + } + + @Test + void getURL() { + assertEquals("", classToTest.getURL()); + + classToTest.addSubroute("routes"); + classToTest.addParameter("parameter", "value"); + + assertEquals("/routes?parameter=value", classToTest.getURL()); + } +} diff --git a/src/test/java/com/meilisearch/sdk/utils/Movie.java b/src/test/java/com/meilisearch/sdk/utils/Movie.java index 153b9d8f..31bf78c9 100644 --- a/src/test/java/com/meilisearch/sdk/utils/Movie.java +++ b/src/test/java/com/meilisearch/sdk/utils/Movie.java @@ -12,7 +12,7 @@ public class Movie { private String language; private String[] genres; private Movie _formatted; - private HashMap> _matchesInfo; + private HashMap> _matchesPosition; public class Match { public int start; @@ -116,11 +116,11 @@ public Movie setFormatted(Movie _formatted) { } public HashMap> getMatchesInfo() { - return _matchesInfo; + return _matchesPosition; } - public Movie setMatchesInfo(HashMap> _matchesInfo) { - this._matchesInfo = _matchesInfo; + public Movie setMatchesInfo(HashMap> _matchesPosition) { + this._matchesPosition = _matchesPosition; return this; } }