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