diff --git a/java/.DS_Store b/java/.DS_Store new file mode 100644 index 0000000..0869a0b Binary files /dev/null and b/java/.DS_Store differ diff --git a/java/README.md b/java/README.md index bbcf903..5f17634 100644 --- a/java/README.md +++ b/java/README.md @@ -31,5 +31,11 @@ Once setup, you can run each of the script in this folder using your favorite Ja | File | Description | | ---------------------------- | -------------------------------------------- | -| [Simple.java](./src/main/java/Simple.java) | Index a single object and run a search query | -| [Indexing.java](./src/main/java/Indexing.java) | Showcase of the main indexing methods | +| [Simple.java](./src/main/java/Simple.java) | Index a single object and run a search query | +| [Indexing.java](./src/main/java/Indexing.java) | Showcase of the main indexing methods | +| [Settings.java](./src/main/java/Settings.java) | Change index settings | +| [Rules.java](./src/main/java/Rules.java) | Export rules and add a new rule to an index | +| [Backup.java](./src/main/java/Backup.java) | Backup an index | +| [Restore.java](./src/main/java/Restore.java) | Restore an index | +| [ReturnTopHits.java](./src/main/java/ReturnTopHits.java) | Get top 1000 searches with Analytics API Client | +| [GenerateKey.java](./src/main/java/GenerateKey.java) | Generate API key | diff --git a/java/pom.xml b/java/pom.xml index 90e1262..43fb9ca 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -21,28 +21,23 @@ - - com.algolia - algoliasearch-core - 3.0.0 - - + com.algolia - algoliasearch-apache - 3.0.0 + algoliasearch + 4.34.2 - org.asynchttpclient - async-http-client - 2.8.1 + io.github.cdimascio + dotenv-java + 3.0.0 - io.github.cdimascio - dotenv-java - 2.2.0 + com.fasterxml.jackson.core + jackson-databind + 2.17.0 diff --git a/java/src/.DS_Store b/java/src/.DS_Store new file mode 100644 index 0000000..a9d14d1 Binary files /dev/null and b/java/src/.DS_Store differ diff --git a/java/src/main/.DS_Store b/java/src/main/.DS_Store new file mode 100644 index 0000000..2b80001 Binary files /dev/null and b/java/src/main/.DS_Store differ diff --git a/java/src/main/java/.DS_Store b/java/src/main/java/.DS_Store new file mode 100644 index 0000000..3fa7933 Binary files /dev/null and b/java/src/main/java/.DS_Store differ diff --git a/java/src/main/java/Backup.java b/java/src/main/java/Backup.java new file mode 100644 index 0000000..44644d9 --- /dev/null +++ b/java/src/main/java/Backup.java @@ -0,0 +1,90 @@ +import java.io.File; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import com.algolia.api.SearchClient; +import com.algolia.model.search.*; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import io.github.cdimascio.dotenv.Dotenv; + +public class Backup { + + public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { + Backup.run(); + } + + public static void run() throws ExecutionException, InterruptedException, IOException { + + Dotenv dotenv = Dotenv.configure().load(); + + String appID = dotenv.get("ALGOLIA_APP_ID"); + String apiKey = dotenv.get("ALGOLIA_API_KEY"); + String indexName = dotenv.get("ALGOLIA_INDEX_NAME"); + + // Start the API client + // https://www.algolia.com/doc/libraries/sdk/methods/search#java + try (SearchClient client = new SearchClient(appID, apiKey)) { + + // Initialize ObjectMapper + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + + // Get all records from an index + // https://www.algolia.com/doc/api-reference/api-methods/browse/#get-all-records-from-an-index + // Use an API key with `browse` ACL + BrowseResponse respRecords = client.browse(indexName, Hit.class); + + // Write records to file + File recordsFile = new File(indexName + "_records.json"); + objectMapper.writeValue(recordsFile, respRecords.getHits()); + + // Retrieve settings for an index + // https://www.algolia.com/doc/api-reference/api-methods/get-settings/#retrieve-settings-for-an-index + + // Export settings + SettingsResponse respSettings = client.getSettings(indexName, 2); + + // Write settings to file + File settingsFile = new File(indexName + "_settings.json"); + objectMapper.writeValue(settingsFile, respSettings); + + // The following settings will export as null if the default value is used and the setting hasn't been modified + // typoTolerance, ignorePlurals, removeStopWords, distinct, reRankingApplyFilter, primary + // Remove these settings if the values are null to prevent errors while restoring + + //Get the file + ObjectNode settingsFileContent = (ObjectNode) objectMapper.readTree(settingsFile); + + // Create array of settings + String[] settingsValues = {"typoTolerance", "ignorePlurals", "removeStopWords", "distinct", "reRankingApplyFilter", "primary"}; + + for (int i = 0; i < settingsValues.length; i++) { + if (settingsFileContent.has(settingsValues[i]) && settingsFileContent.get(settingsValues[i]).isNull()) { + settingsFileContent.remove(settingsValues[i]); + } + } + + objectMapper.writeValue(settingsFile, settingsFileContent); + + // Export rules + // https://www.algolia.com/doc/api-reference/api-methods/export-rules/ + Iterable respRules = client.browseRules(indexName, new SearchRulesParams()); + + // Transform rules iterator to Array and then to JSON + File rulesFile = new File(indexName + "_rules.json"); + objectMapper.writeValue(rulesFile, respRules); + + // Export synonyms + // https://www.algolia.com/doc/api-reference/api-methods/export-synonyms/ + Iterable respSynonyms = client.browseSynonyms(indexName, new SearchSynonymsParams()); + + // Transform synonyms iterator to Array and then to JSON + File synonymsFile = new File(indexName + "_synonyms.json"); + objectMapper.writeValue(synonymsFile, respSynonyms); + + } + } +} diff --git a/java/src/main/java/Contact.java b/java/src/main/java/Contact.java index fc48bb5..4bcc262 100644 --- a/java/src/main/java/Contact.java +++ b/java/src/main/java/Contact.java @@ -33,6 +33,11 @@ public Contact setEmail(String email) { return this; } + public Contact setObjectID(String objectID) { + this.objectID = objectID; + return this; + } + public String getObjectID() { return objectID; } diff --git a/java/src/main/java/GenerateKey.java b/java/src/main/java/GenerateKey.java new file mode 100644 index 0000000..3760276 --- /dev/null +++ b/java/src/main/java/GenerateKey.java @@ -0,0 +1,65 @@ +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.ExecutionException; + +import com.algolia.api.SearchClient; +import com.algolia.model.search.*; + +import io.github.cdimascio.dotenv.Dotenv; + +public class GenerateKey { + + public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { + GenerateKey.run(); + } + + public static void run() throws ExecutionException, InterruptedException, IOException { + + Dotenv dotenv = Dotenv.configure().load(); + + String appID = dotenv.get("ALGOLIA_APP_ID"); + String apiKey = dotenv.get("ALGOLIA_API_KEY"); + String indexName = dotenv.get("ALGOLIA_INDEX_NAME"); + + // Start the API client + // https://www.algolia.com/doc/libraries/sdk/methods/search#java + try (SearchClient client = new SearchClient(appID, apiKey)) { + + // Create a new restricted search-only API key + AddApiKeyResponse apiKeyResp = client.addApiKey( + new ApiKey() + .setAcl(Arrays.asList(Acl.SEARCH, Acl.ADD_OBJECT)) + .setDescription("Restricted search-only API key for algolia.com") + .setMaxQueriesPerIPPerHour(100) + ); + + client.waitForApiKey(apiKeyResp.getKey(), ApiKeyOperation.ADD); + + // Make sure new key has been created + String newKey = apiKeyResp.getKey(); + + if (newKey == apiKeyResp.getKey()) { + System.out.println("Key generated successfully: " + newKey); + } else { + System.out.println("Error while creating key\n"); + } + + // Test the created key + System.out.println("Testing key"); + + // Initialise a new client with the generated key + SearchClient newClient = new SearchClient(appID, newKey); + + // Test the new generated key by performing a search + try { + SearchResponse newKeySearchResp = newClient.searchSingleIndex(indexName, Hit.class); + System.out.println(newKeySearchResp.getHits()); + } + catch(Exception e) { + System.out.println("Failed search with the new key\n"); + } + + newClient.close(); + } + } +} \ No newline at end of file diff --git a/java/src/main/java/Indexing.java b/java/src/main/java/Indexing.java index 01e6277..97e773d 100644 --- a/java/src/main/java/Indexing.java +++ b/java/src/main/java/Indexing.java @@ -1,19 +1,14 @@ -import com.algolia.search.*; -import com.algolia.search.models.indexing.BatchIndexingResponse; -import com.algolia.search.models.indexing.Query; -import com.algolia.search.models.indexing.SearchResult; -import com.algolia.search.models.settings.IndexSettings; -import com.algolia.search.models.indexing.BatchOperation; -import com.algolia.search.models.indexing.BatchRequest; -import com.algolia.search.models.indexing.ActionEnum; import java.io.IOException; -import java.lang.StackWalker.Option; -import java.util.List; import java.util.Arrays; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; + +import com.algolia.api.SearchClient; +import com.algolia.model.search.*; + import io.github.cdimascio.dotenv.Dotenv; public class Indexing { @@ -26,14 +21,13 @@ public static void run() throws ExecutionException, InterruptedException, IOExce Dotenv dotenv = Dotenv.configure().load(); - // Start the API client - // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ - try (SearchClient searchClient = - DefaultSearchClient.create(dotenv.get("ALGOLIA_APP_ID"), dotenv.get("ALGOLIA_API_KEY"))) { + String appID = dotenv.get("ALGOLIA_APP_ID"); + String apiKey = dotenv.get("ALGOLIA_API_KEY"); + String indexName = dotenv.get("ALGOLIA_INDEX_NAME"); - // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) - // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index - SearchIndex index = searchClient.initIndex(dotenv.get("ALGOLIA_INDEX_NAME"), Contact.class); + // Start the API client + // https://www.algolia.com/doc/libraries/sdk/methods/search#java + try (SearchClient client = new SearchClient(appID, apiKey)) { // Define some objects to add to our index // https://www.algolia.com/doc/api-client/methods/indexing/#object-and-record @@ -43,43 +37,57 @@ public static void run() throws ExecutionException, InterruptedException, IOExce ); // We don't have any objects (yet) in our index - SearchResult searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + CompletableFuture> searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); // Save Objects: Add mutliple new objects to an index. // https://www.algolia.com/doc/api-reference/api-methods/add-objects/?client=java System.out.println("Save Objects - Adding multiple objects: " + contacts); - index.saveObjects(contacts, true).waitTask(); - - searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + + List saveObjects = client.saveObjects(indexName,contacts); + + client.waitForTask(indexName, saveObjects.get(0).getTaskID()); + + searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); // Save Objects: Replace an existing object with an updated set of attributes. // https://www.algolia.com/doc/api-reference/api-methods/save-objects/?client=java System.out.println("Save Objects - Replacing objects’s attributes on: " + contacts.get(0)); Contact firstContact = contacts.get(0).setName("FooBar"); - index.saveObject(firstContact).waitTask(); + SaveObjectResponse saveObj = client.saveObject(indexName,firstContact); + + client.waitForTask(indexName, saveObj.getTaskID()); - searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); // Partial Update Objects: Update one or more attributes of an existing object. // https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/?client=java System.out.println("Save Objects - Updating object’s attributes on: " + contacts.get(0)); firstContact.setEmail("test@test.com"); - index.partialUpdateObject(firstContact).waitTask(); - searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + UpdatedAtWithObjectIdResponse partialUpdateResp = client.partialUpdateObject( + indexName, + firstContact.getObjectID(), + firstContact + ); + + client.waitForTask(indexName, partialUpdateResp.getTaskID()); + + searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); // Delete Objects: Remove objects from an index using their objectID. // https://www.algolia.com/doc/api-reference/api-methods/delete-objects/?client=java String objectIDToDelete = contacts.get(0).getObjectID(); System.out.println("Delete Objects - Deleting object with objectID: " + objectIDToDelete); - index.deleteObject(objectIDToDelete).waitTask(); + List deleteObjResp = client.deleteObjects(indexName, Arrays.asList(objectIDToDelete)); + + client.waitForTask(indexName, deleteObjResp.get(0).getTaskID()); - searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); // Replace All Objects: Clears all objects from your index and replaces them with a new set of objects. // https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/?client=java @@ -88,10 +96,17 @@ public static void run() throws ExecutionException, InterruptedException, IOExce new Contact("4", "NewBar", Optional.empty()) ); System.out.println("Replace All Objects - Clears all objects and replaces them with: " + newContacts); - index.replaceAllObjects(newContacts, true); + ReplaceAllObjectsResponse replaceAllObjResp = client.replaceAllObjects( + indexName, + newContacts, + 2, + Arrays.asList(ScopeType.SETTINGS, ScopeType.SYNONYMS) + ); + + client.waitForTask(indexName, replaceAllObjResp.getBatchResponses().get(0).getTaskID()); - searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); // Delete By: Remove all objects matching a filter (including geo filters). // https://www.algolia.com/doc/api-reference/api-methods/delete-by/?client=java @@ -101,41 +116,69 @@ public static void run() throws ExecutionException, InterruptedException, IOExce // https://www.algolia.com/doc/api-client/methods/settings/?client=java IndexSettings settings = new IndexSettings(); settings.setAttributesForFaceting(Arrays.asList("name")); - index.setSettings(settings).waitTask(); + + UpdatedAtResponse response = client.setSettings( + indexName, + settings, + true + ); + + client.waitForTask(indexName, response.getTaskID()); // Now delete the records matching "name=NewBar" - index.deleteBy(new Query("").setFacetFilters(Arrays.asList(Arrays.asList("name:NewBar")))); + response = client.deleteBy(indexName, new DeleteByParams().setFilters("name:NewBar")); + + client.waitForTask(indexName, response.getTaskID()); - searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); // Get Objects: Get one or more objects using their objectIDs. // https://www.algolia.com/doc/api-reference/api-methods/get-objects/?client=java String objectIDToRetrieve = newContacts.get(0).getObjectID(); System.out.println("Get Objects - Getting object with objectID: " + objectIDToRetrieve); - Contact contact = index.getObject(objectIDToRetrieve); - System.out.println("Result: " + contact); + Object getObjResp = client.getObject(indexName, objectIDToRetrieve); + System.out.println("Result: " + getObjResp); // Custom Batch: Perform several indexing operations in one API call. // https://www.algolia.com/doc/api-reference/api-methods/batch/?client=java - List> operations = Arrays.asList( - new BatchOperation<>(dotenv.get("ALGOLIA_INDEX_NAME"), ActionEnum.ADD_OBJECT, new Contact("3", "BatchedBar", Optional.empty())), - new BatchOperation<>(dotenv.get("ALGOLIA_INDEX_NAME"), ActionEnum.UPDATE_OBJECT, new Contact("4", "BatchedFoo", Optional.empty())) + BatchWriteParams operations = new BatchWriteParams().setRequests( + Arrays.asList( + new BatchRequest() + .setAction(Action.ADD_OBJECT) + .setBody( + new Contact("3", "BatchedBar", Optional.empty()) + ), + new BatchRequest() + .setAction(Action.ADD_OBJECT) + .setBody( + new Contact("4", "BatchedFoo", Optional.empty()) + ) + ) + ); + + BatchResponse batchResp = client.batch( + indexName, + operations ); + System.out.println("Custom Batch"); - searchClient.multipleBatch(operations).waitTask(); + client.waitForTask(indexName, batchResp.getTaskID()); - searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); // Clear Objects: Clear the records of an index without affecting its settings. // https://www.algolia.com/doc/api-reference/api-methods/clear-objects/?client=java System.out.println("Clear objects"); - index.clearObjects().waitTask(); + response = client.clearObjects(indexName); + + client.waitForTask(indexName, response.getTaskID()); - searchResults = index.search(new Query("")); - System.out.println("Current objects: " + searchResults.getHits()); + searchResults = client.searchSingleIndexAsync(indexName, Hit.class); + System.out.println("Current objects: " + searchResults.get().getHits()); + } } } \ No newline at end of file diff --git a/java/src/main/java/Restore.java b/java/src/main/java/Restore.java new file mode 100644 index 0000000..801c6ab --- /dev/null +++ b/java/src/main/java/Restore.java @@ -0,0 +1,95 @@ +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutionException; + +import com.algolia.api.SearchClient; +import com.algolia.model.search.*; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.github.cdimascio.dotenv.Dotenv; + +public class Restore { + + public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { + Restore.run(); + } + + public static void run() throws ExecutionException, InterruptedException, IOException { + + Dotenv dotenv = Dotenv.configure().load(); + + String appID = dotenv.get("ALGOLIA_APP_ID"); + String apiKey = dotenv.get("ALGOLIA_API_KEY"); + String indexName = dotenv.get("ALGOLIA_INDEX_NAME"); + + // Start the API client + // https://www.algolia.com/doc/libraries/sdk/methods/search#java + try (SearchClient client = new SearchClient(appID, apiKey)) { + + ObjectMapper objectMapper = new ObjectMapper(); + + // Restoring all records with replace all objects method + // https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/ + + // Read json file + Iterable recordsList = objectMapper.readValue(new FileInputStream(indexName + "_records.json"), new TypeReference>() {}); + + // Restore Records + client.replaceAllObjects( + indexName, + recordsList, + 77, + Arrays.asList(ScopeType.SETTINGS, ScopeType.SYNONYMS) + ); + + // Restoring settings with set settings method + // https://www.algolia.com/doc/api-reference/api-methods/set-settings/ + + // Read json file + IndexSettings settings = objectMapper.readValue(new File(indexName + "_settings.json"), IndexSettings.class); + + // Restore settings + client.setSettings( + indexName, + settings, + true + ); + + // Restoring Rules with replace all rules method + // https://www.algolia.com/doc/api-reference/api-methods/replace-all-rules/ + + // Read json file + List rulesList = objectMapper.readValue(new FileInputStream(indexName + "_rules.json"), new TypeReference>() {}); + + // Restore Rules + UpdatedAtResponse rulesResp = client.saveRules( + indexName, + rulesList, + true, + false + ); + + client.waitForTask(indexName, rulesResp.getTaskID()); + + // Restoring Synonyms with replace all synonyms method + // https://www.algolia.com/doc/api-reference/api-methods/replace-all-synonyms/?client=php + + // Read json file + List synonymsList = objectMapper.readValue(new FileInputStream(indexName + "_synonyms.json"), new TypeReference>() {}); + + // Restore Synonyms + UpdatedAtResponse synonymsResp = client.saveSynonyms( + indexName, + synonymsList, + true, + true + ); + + client.waitForTask(indexName, synonymsResp.getTaskID()); + } + } +} \ No newline at end of file diff --git a/java/src/main/java/ReturnTopHits.java b/java/src/main/java/ReturnTopHits.java new file mode 100644 index 0000000..d7fa435 --- /dev/null +++ b/java/src/main/java/ReturnTopHits.java @@ -0,0 +1,60 @@ +import java.io.File; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import com.algolia.api.AnalyticsClient; +import com.algolia.config.*; +import com.algolia.model.analytics.GetTopSearchesResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +import io.github.cdimascio.dotenv.Dotenv; + +public class ReturnTopHits { + + public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { + ReturnTopHits.run(); + } + + public static void run() throws ExecutionException, InterruptedException, IOException { + + Dotenv dotenv = Dotenv.configure().load(); + + // Pick a region for your analytics + // us for the United States or de for Europe + + String appID = dotenv.get("ALGOLIA_APP_ID"); + String apiKey = dotenv.get("ALGOLIA_API_KEY"); + String indexName = dotenv.get("ALGOLIA_INDEX_NAME"); + String analyticsRegion = "us"; + + // Start the API client + // https://www.algolia.com/doc/libraries/sdk/methods/analytics + // Initialize the client with your application region, eg. analytics.ALGOLIA_APPLICATION_REGION + try (AnalyticsClient client = new AnalyticsClient(appID, apiKey, analyticsRegion)) { + // Initialize ObjectMapper + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + + RequestOptions options = new RequestOptions(); + options.addExtraQueryParameters("limit",1000); + GetTopSearchesResponse topSearchResp = client.getTopSearches( + indexName, + null, // clickAnalytics + null, // revenueAnalytics + null, // startDate + null, // endDate + null, // orderBy + null, // direction + 1000, + null, + null // tags + ); + + System.out.println(topSearchResp); + + File recordsFile = new File(indexName + "__top_1000_searches.json"); + objectMapper.writeValue(recordsFile, topSearchResp); + } + } +} \ No newline at end of file diff --git a/java/src/main/java/Rules.java b/java/src/main/java/Rules.java new file mode 100644 index 0000000..c7c8f96 --- /dev/null +++ b/java/src/main/java/Rules.java @@ -0,0 +1,65 @@ +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.ExecutionException; + +import com.algolia.api.SearchClient; +import com.algolia.model.search.*; + +import io.github.cdimascio.dotenv.Dotenv; + +public class Rules { + + public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { + Rules.run(); + } + + public static void run() throws ExecutionException, InterruptedException, IOException { + + Dotenv dotenv = Dotenv.configure().load(); + + String appID = dotenv.get("ALGOLIA_APP_ID"); + String apiKey = dotenv.get("ALGOLIA_API_KEY"); + String indexName = dotenv.get("ALGOLIA_INDEX_NAME"); + + // Start the API client + // https://www.algolia.com/doc/libraries/sdk/methods/search#java + try (SearchClient client = new SearchClient(appID, apiKey)) { + // Exporting the rules + // https://www.algolia.com/doc/api-reference/api-methods/export-rules/#examples + System.out.println("Original rules:\n"); + Iterable response = client.browseRules(indexName, new SearchRulesParams()); + + for (Rule rule : response) { + System.out.println("- Rule: " + rule.getObjectID()); + } + + String ruleID = "a-rule-id"; + + Rule newRule = new Rule() + .setObjectID(ruleID) + .setConditions(Arrays.asList(new Condition().setPattern("flower").setAnchoring(Anchoring.CONTAINS))) + .setConsequence(new Consequence().setPromote(Arrays.asList(new PromoteObjectID().setObjectID("439957720").setPosition(0)))); + + // Adding a new rule + // https://www.algolia.com/doc/api-reference/api-methods/save-rule/#save-a-rule + UpdatedAtResponse saveRuleResp = client.saveRule( + indexName, + ruleID, + newRule + ); + + client.waitForTask(indexName, saveRuleResp.getTaskID()); + + // Exporting the modified rules + // https://www.algolia.com/doc/api-reference/api-methods/export-rules/#examples + System.out.println("Updated rules:\n"); + response = client.browseRules(indexName, new SearchRulesParams()); + + for (Rule rule : response) { + System.out.println("- Rule: " + rule.getObjectID()); + } + + client.close(); + } + } +} diff --git a/java/src/main/java/Settings.java b/java/src/main/java/Settings.java new file mode 100644 index 0000000..66dc0ca --- /dev/null +++ b/java/src/main/java/Settings.java @@ -0,0 +1,48 @@ +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.ExecutionException; + +import com.algolia.api.SearchClient; +import com.algolia.model.search.*; + +import io.github.cdimascio.dotenv.Dotenv; + +public class Settings { + + public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { + Settings.run(); + } + + public static void run() throws ExecutionException, InterruptedException, IOException { + + Dotenv dotenv = Dotenv.configure().load(); + + String appID = dotenv.get("ALGOLIA_APP_ID"); + String apiKey = dotenv.get("ALGOLIA_API_KEY"); + String indexName = dotenv.get("ALGOLIA_INDEX_NAME"); + + // Start the API client + // https://www.algolia.com/doc/libraries/sdk/methods/search#java + try (SearchClient client = new SearchClient(appID, apiKey)) { + // Set index settings + // https://www.algolia.com/doc/api-reference/api-methods/set-settings/ + IndexSettings settings = new IndexSettings(); + settings.setSearchableAttributes(Arrays.asList("actors","genre")).setCustomRanking(Arrays.asList("desc(rating)")); + + UpdatedAtResponse response = client.setSettings( + indexName, + settings, + true + ); + + client.waitForTask(indexName, response.getTaskID()); + + // Printing settings + // https://www.algolia.com/doc/api-reference/api-methods/get-settings/ + SettingsResponse settingsResp = client.getSettings(indexName, 2); + + // print the response + System.out.println(settingsResp); + } + } +} diff --git a/java/src/main/java/Simple.java b/java/src/main/java/Simple.java index e0dc159..609eef7 100644 --- a/java/src/main/java/Simple.java +++ b/java/src/main/java/Simple.java @@ -1,8 +1,7 @@ -import com.algolia.search.*; -import com.algolia.search.models.indexing.BatchIndexingResponse; -import com.algolia.search.models.indexing.Query; -import com.algolia.search.models.indexing.SearchResult; +import com.algolia.api.SearchClient; +import com.algolia.model.search.*; import java.io.IOException; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import io.github.cdimascio.dotenv.Dotenv; @@ -17,30 +16,32 @@ public static void run() throws ExecutionException, InterruptedException, IOExce Dotenv dotenv = Dotenv.configure().load(); + String appID = dotenv.get("ALGOLIA_APP_ID"); + String apiKey = dotenv.get("ALGOLIA_API_KEY"); + String indexName = dotenv.get("ALGOLIA_INDEX_NAME"); + // Start the API client // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ - try (SearchClient searchClient = - DefaultSearchClient.create(dotenv.get("ALGOLIA_APP_ID"), dotenv.get("ALGOLIA_API_KEY"))) { + try (SearchClient client = new SearchClient(appID, apiKey)) { - // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) - // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index - SearchIndex index = searchClient.initIndex(dotenv.get("ALGOLIA_INDEX_NAME"), Contact.class); - // Add new objects to the index // https://www.algolia.com/doc/api-reference/api-methods/add-objects/ - Contact contact = new Contact("1", "Foo", null); - CompletableFuture indexingFuture = index.saveObjectAsync(contact, true); + Contact contact = new Contact("1", "Foo", Optional.empty()); + + SaveObjectResponse saveResp = client.saveObject( + indexName, + contact + ); // Wait for the indexing task to complete // https://www.algolia.com/doc/api-reference/api-methods/wait-task/ - indexingFuture.get(); + client.waitForTask(indexName, saveResp.getTaskID()); // Search the index for "Fo" // https://www.algolia.com/doc/api-reference/api-methods/search/ - CompletableFuture> searchAlgoliaFuture = - index.searchAsync(new Query("Foo")); + CompletableFuture> respSearch = client.searchSingleIndexAsync(indexName, Hit.class); - System.out.println("Search results:" + searchAlgoliaFuture.get().getHits()); + System.out.println("Search results:" + respSearch.get().getHits()); } } } \ No newline at end of file