Skip to content
Draft
69 changes: 36 additions & 33 deletions javascript/backup_index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ This script will export an index, including records, settings, rules and synonym
It can be used in conjunction with restore.js to backup and restore an index to an application.
*/

// Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript
const algoliasearch = require("algoliasearch");
const dotenv = require("dotenv");

dotenv.config();
// Install the API client: https://www.algolia.com/doc/libraries/sdk/install#javascript
import { algoliasearch } from "algoliasearch";
import "dotenv/config";
import * as fs from "fs";

// Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys
// and choose a name for your index. Add these environment variables to a `.env` file:
Expand All @@ -17,68 +16,71 @@ const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY;
const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME;

// Start the API client
// https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/
// https://www.algolia.com/doc/libraries/sdk/install#test-your-installation
const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY);

// 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
const index = client.initIndex(ALGOLIA_INDEX_NAME);

// Requiring fs module in which writeFile function is defined.
const fs = require("fs");
// Create an index name (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists)
// https://www.algolia.com/doc/libraries/sdk/install#test-your-installation
const indexName = ALGOLIA_INDEX_NAME || "new_index_name";

let records = [],
settings = [],
rules = [],
synonyms = [];

(async () => {
// retrieve all records from index
console.log(`Retrieving records...`);
try {
await index.browseObjects({
batch: (batch) => {
records = records.concat(batch);
}
console.log(`Retrieving records...`);

// retrieve all records from index
// https://www.algolia.com/doc/libraries/sdk/methods/search/browse-objects#javascript
await client.browseObjects({
indexName,
aggregator: (res) => {
records.push(...res.hits);
},
});

console.log(`${records.length} records retrieved`);
console.log(`${records.length} record(s) retrieved`);

console.log(`Retrieving settings...`);

// retrieve all index settings
settings = await index.getSettings().then();
// https://www.algolia.com/doc/libraries/sdk/methods/search/get-settings
settings = await client.getSettings({ indexName: indexName }).then();

console.log(`settings retrieved`);

console.log(`Retrieving rules...`);

// retrieve all rules for index
await index
.browseRules({
batch: (batch) => {
rules = rules.concat(batch);
}
});
// https://www.algolia.com/doc/libraries/sdk/methods/search/browse-rules
await client.browseRules({
indexName,
aggregator: (res) => {
rules.push(...res.hits);
},
});

console.log(`${rules.length} rules retrieved`);

console.log(`Retrieving synonyms...`);

// retrieve all synonyms for index
await index
.browseSynonyms({
batch: (batch) => {
synonyms = synonyms.concat(batch);
},
});
// https://www.algolia.com/doc/libraries/sdk/methods/search/browse-synonyms
await client.browseSynonyms({
indexName,
aggregator: (res) => {
synonyms.push(...res.hits);
},
});

console.log(`${synonyms.length} synonyms retrieved`);
} catch (error) {
console.log(`Error retrieving data ${error.message}`);
}

// write json files to current directory
// write json files to current directory
function createJson(data, name) {
if (data) {
fs.writeFile(
Expand All @@ -93,6 +95,7 @@ let records = [],
console.log(`Error writing files: ${error.message}`);
};
}

try {
let name = "records";
createJson(records, name);
Expand Down
68 changes: 38 additions & 30 deletions javascript/change_index_settings.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript
const algoliasearch = require("algoliasearch");
const dotenv = require("dotenv");

dotenv.config();
// Install the API client: https://www.algolia.com/doc/libraries/sdk/install#javascript
import { algoliasearch } from "algoliasearch";
import "dotenv/config";

// Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys
// and choose a name for your index. Add these environment variables to a `.env` file:
Expand All @@ -11,32 +9,42 @@ const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY;
const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME;

// Start the API client
// https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/
// https://www.algolia.com/doc/libraries/sdk/install#test-your-installation
const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY);

// 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
const index = client.initIndex(ALGOLIA_INDEX_NAME);

// Changes an index's settings, Only specified settings are overridden; unspecified settings are left unchanged
// https://www.algolia.com/doc/api-reference/api-methods/set-settings/#about-this-method
index
.setSettings({
searchableAttributes: ["name", "city"],
customRanking: ["desc(followers)"],
}, {
// Option to forward the same settings to the replica indices.
forwardToReplicas: true
})
// Wait for the indexing task to complete
// https://www.algolia.com/doc/api-reference/api-methods/wait-task/
.wait()
.then((response) => {
// Display response (updatedAt, taskID)
// Create an index name (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists)
// https://www.algolia.com/doc/libraries/sdk/install#test-your-installation
const indexName = ALGOLIA_INDEX_NAME || "new_index_name";

// Changes an index's settings. Only specified settings are overridden; unspecified settings are left unchanged
// https://www.algolia.com/doc/libraries/sdk/methods/search/set-settings

(async () => {
try {
const response = await client.setSettings({
indexName: indexName,
indexSettings: { paginationLimitedTo: 10, typoTolerance: "false" },
// Option to forward the same settings to the replica indices.
forwardToReplicas: true,
});

// print the response
console.log(response);
// Display both changed settings
index.getSettings().then((settings) => {
console.log(settings["searchableAttributes"], settings["customRanking"]);

// Wait for the indexing task to complete
// https://www.algolia.com/doc/libraries/sdk/methods/search/wait-for-task
await client.waitForTask({ indexName: indexName, taskID: response.taskID });

// Get the index settings
// https://www.algolia.com/doc/libraries/sdk/methods/search/get-settings
const settings = await client.getSettings({
indexName: indexName,
getVersion: 2,
});
})
.catch((error) => console.log(error));

// Display both changed settings
console.log(settings["paginationLimitedTo"], settings["typoTolerance"]);
} catch (error) {
console.log(`Error retrieving data ${error.message}`);
}
})();
111 changes: 53 additions & 58 deletions javascript/export_and_add_rule_to_index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
// Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript
const algoliasearch = require("algoliasearch");
const dotenv = require("dotenv");
// Requiring fs module in which writeFile function is defined.
const fs = require("fs");

dotenv.config();
// Install the API client: https://www.algolia.com/doc/libraries/sdk/install#javascript
import { algoliasearch } from "algoliasearch";
import "dotenv/config";
import * as fs from "fs";

// Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys
// and choose a name for your index. Add these environment variables to a `.env` file:
Expand All @@ -13,70 +10,68 @@ const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY;
const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME;

// Start the API client
// https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/
// https://www.algolia.com/doc/libraries/sdk/install#test-your-installation
const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY);

// 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
const index = client.initIndex(ALGOLIA_INDEX_NAME);
// Create an index name (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists)
// https://www.algolia.com/doc/libraries/sdk/install#test-your-installation
const indexName = ALGOLIA_INDEX_NAME || "new_index_name";

// Export Rules for this index
// https://www.algolia.com/doc/api-reference/api-methods/export-rules/
index
.browseRules({
// A `batch` callback function that's called on every batch of rules
batch: (batch) =>
// Export JSON file containing Rules into same directory with prefix of index_name
(async () => {
// Export Rules for this index
// https://www.algolia.com/doc/libraries/sdk/methods/search/browse-rules
await client.browseRules({
indexName,
aggregator: (res) =>
fs.writeFile(
`${ALGOLIA_INDEX_NAME}_rules.json`,
JSON.stringify(batch),
JSON.stringify(res.hits),
(err) => {
// In case of a error throw err.
if (err) throw err;
}
),
})
.then((response) => {
// Success message
console.log(
`Rules saved as ${ALGOLIA_INDEX_NAME}_rules.json in the current directory`
);
})
.catch((error) => console.log(error));
});

// Create a rule
const rule = {
objectID: "a-rule-id",
conditions: [
{
pattern: "Jimmie",
anchoring: "is",
},
],
consequence: {
params: {
filters: "zip_code = 12345",
console.log(
`Rules saved as ${ALGOLIA_INDEX_NAME}_rules.json in the current directory`
);

// Create a rule
const rule = {
objectID: "a-rule-id",
conditions: [
{
pattern: "Jimmie",
anchoring: "is",
},
],
consequence: {
params: {
filters: "zip_code = 12345",
},
},
},

// Optionally, to disable the rule change to 'false'
enabled: true,
// Optionally, to disable the rule change to 'false'
enabled: true,

// Optionally, to add valitidy time ranges
validity: [
{
from: Math.floor(Date.now() / 1000),
until: Math.floor(Date.now() / 1000) + 10 * 24 * 60 * 60,
},
],
};
// Optionally, to add valitidy time ranges
validity: [
{
from: Math.floor(Date.now() / 1000),
until: Math.floor(Date.now() / 1000) + 10 * 24 * 60 * 60,
},
],
};

// Save the Rule.
index.saveRule(rule).then(() => {
// done
});
// Save the Rule, and forward it to all replicas of the index.
const response = await client.saveRule({
indexName: indexName,
objectID: "a-rule-id",
forwardToReplicas: true,
rule: rule,
});

// Save the Rule, and forward it to all replicas of the index.
index.saveRule(rule, { forwardToReplicas: true }).then(() => {
// done
});
// Log the response
console.log(response);
})();
Loading