├── .gitignore ├── .vscode └── .extensions.json ├── README.md ├── dotnet ├── .devcontainer │ ├── Dockerfile │ └── devcontainer.json ├── .env.example ├── .gitignore ├── Contact.cs ├── Program.cs ├── README.md └── dotnet.csproj ├── go ├── .devcontainer │ ├── Dockerfile │ └── devcontainer.json ├── .env.example ├── README.md ├── generate_key.go ├── go.mod ├── go.sum ├── indexing.go └── simple.go ├── java ├── .devcontainer │ ├── Dockerfile │ └── devcontainer.json ├── .env.example ├── .vscode │ └── settings.json ├── README.md ├── pom.xml └── src │ └── main │ └── java │ ├── Contact.java │ ├── Indexing.java │ └── Simple.java ├── javascript ├── .devcontainer │ ├── Dockerfile │ └── devcontainer.json ├── .env.example ├── README.md ├── backup_index.js ├── change_index_settings.js ├── export_and_add_rule_to_index.js ├── generate_key.js ├── indexing.js ├── list_indices_and_record_size.js ├── package-lock.json ├── package.json ├── rest_API_return_top_1000_hits.js ├── restore_index.js ├── simple.js ├── sort_index_by_record_size.js └── yarn.lock ├── package-lock.json ├── php ├── .devcontainer │ ├── Dockerfile │ └── devcontainer.json ├── .dockerignore ├── .env.example ├── README.md ├── backup.php ├── change_index_settings.php ├── composer.json ├── composer.lock ├── generate_key.php ├── indexing.php ├── rest_api_return_top_hits.php ├── restore.php ├── rules.php └── simple.php ├── python ├── .devcontainer │ ├── Dockerfile │ └── devcontainer.json ├── .env.example ├── README.md ├── analytics-backup.py ├── analytics.py ├── backup.py ├── generate_key.py ├── indexing.py ├── requirements.txt ├── restore.py ├── set_settings.py └── simple.py ├── ruby ├── .devcontainer │ ├── Dockerfile │ └── devcontainer.json ├── .env.example ├── Gemfile ├── Gemfile.lock ├── README.md ├── backup_index.rb ├── export_and_add_rule_to_index.rb ├── generate_key.rb ├── index_settings.rb ├── indexing.rb ├── rules.rb └── simple.rb └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | 3 | # PHP 4 | vendor/ 5 | .composer.lock 6 | 7 | # Python 8 | env/ 9 | 10 | # Go 11 | 12 | # Ruby 13 | debug.log 14 | 15 | # Javascript 16 | node_modules/ 17 | 18 | # Java 19 | target/ 20 | .classpath 21 | .project 22 | .settings/ -------------------------------------------------------------------------------- /.vscode/.extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-vscode-remote.remote-containers" 4 | ] 5 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # API Clients Samples 2 | 3 | This repository contains a collection of samples showcasing some typical uses of the Algolia API Clients & Integrations. 4 | 5 | ## Prerequisites 6 | 7 | To learn how to get started with Algolia, you can take a look at our [getting started guide](https://www.algolia.com/doc/guides/getting-started/quick-start/), or just trying out one of the API Client quickstart for the language or framework of your choice. 8 | 9 | ## Quickstarts 10 | 11 | ### [Python](/python) 12 | 13 | This quickstart sample demonstrates usages of the [Algolia Python SDK](https://www.algolia.com/doc/api-client/getting-started/install/python/?client=python). 14 | 15 | ### [Go](/go) 16 | 17 | This quickstart sample demonstrates usages of the [Algolia Go SDK](https://www.algolia.com/doc/api-client/getting-started/install/go/?client=go). 18 | 19 | ### [PHP](/php) 20 | 21 | This quickstart sample demonstrates usages of the [Algolia PHP SDK](https://www.algolia.com/doc/api-client/getting-started/install/php/?client=php). 22 | 23 | ### [JavaScript](/javascript) 24 | 25 | This quickstart sample demonstrates usages of the [Algolia Javascript SDK](https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript). 26 | 27 | ### [.NET](/dotnet) 28 | 29 | This quickstart sample demonstrates usages of the [Algolia .NET SDK](https://www.algolia.com/doc/api-client/getting-started/install/csharp/?client=csharp). 30 | 31 | ### [JAVA](/java) 32 | 33 | This quickstart sample demonstrates usages of the [Algolia Java SDK](https://www.algolia.com/doc/api-client/getting-started/install/java/?client=java). 34 | 35 | ### [RUBY](/ruby) 36 | 37 | This quickstart sample demonstrates usages of the [Algolia Ruby SDK](https://www.algolia.com/doc/api-client/getting-started/install/ruby/?client=ruby). 38 | -------------------------------------------------------------------------------- /dotnet/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] .NET version: 5.0, 3.1, 2.1 2 | ARG VARIANT=3.1 3 | FROM mcr.microsoft.com/vscode/devcontainers/dotnet:0-${VARIANT} 4 | 5 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 6 | ARG NODE_VERSION="none" 7 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 8 | 9 | # [Optional] Uncomment this section to install additional OS packages. 10 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 11 | # && apt-get -y install --no-install-recommends 12 | 13 | # [Optional] Uncomment this line to install global node packages. 14 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /dotnet/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "C# (.NET)", 3 | "runArgs": ["--init"], 4 | "build": { 5 | "dockerfile": "Dockerfile", 6 | "args": { 7 | // Update 'VARIANT' to pick a .NET Core version: 2.1, 3.1, 5.0 8 | "VARIANT": "5.0", 9 | // Options 10 | "NODE_VERSION": "lts/*", 11 | "INSTALL_AZURE_CLI": "false" 12 | } 13 | }, 14 | 15 | // Set *default* container specific settings.json values on container create. 16 | "settings": {}, 17 | 18 | // Add the IDs of extensions you want installed when the container is created. 19 | "extensions": [ 20 | "ms-dotnettools.csharp" 21 | ], 22 | 23 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 24 | // "forwardPorts": [5000, 5001], 25 | 26 | // [Optional] To reuse of your local HTTPS dev cert: 27 | // 28 | // 1. Export it locally using this command: 29 | // * Windows PowerShell: 30 | // dotnet dev-certs https --trust; dotnet dev-certs https -ep "$env:USERPROFILE/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere" 31 | // * macOS/Linux terminal: 32 | // dotnet dev-certs https --trust; dotnet dev-certs https -ep "${HOME}/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere" 33 | // 34 | // 2. Uncomment these 'remoteEnv' lines: 35 | // "remoteEnv": { 36 | // "ASPNETCORE_Kestrel__Certificates__Default__Password": "SecurePwdGoesHere", 37 | // "ASPNETCORE_Kestrel__Certificates__Default__Path": "/home/vscode/.aspnet/https/aspnetapp.pfx", 38 | // }, 39 | // 40 | // 3. Do one of the following depending on your scenario: 41 | // * When using GitHub Codespaces and/or Remote - Containers: 42 | // 1. Start the container 43 | // 2. Drag ~/.aspnet/https/aspnetapp.pfx into the root of the file explorer 44 | // 3. Open a terminal in VS Code and run "mkdir -p /home/vscode/.aspnet/https && mv aspnetapp.pfx /home/vscode/.aspnet/https" 45 | // 46 | // * If only using Remote - Containers with a local container, uncomment this line instead: 47 | // "mounts": [ "source=${env:HOME}${env:USERPROFILE}/.aspnet/https,target=/home/vscode/.aspnet/https,type=bind" ], 48 | 49 | // Use 'postCreateCommand' to run commands after the container is created. 50 | // "postCreateCommand": "dotnet restore", 51 | 52 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 53 | "remoteUser": "vscode", 54 | "postStartCommand": "dotnet restore", 55 | } -------------------------------------------------------------------------------- /dotnet/.env.example: -------------------------------------------------------------------------------- 1 | ALGOLIA_APP_ID= 2 | ALGOLIA_API_KEY= 3 | ALGOLIA_INDEX_NAME= -------------------------------------------------------------------------------- /dotnet/.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # Tye 66 | .tye/ 67 | 68 | # ASP.NET Scaffolding 69 | ScaffoldingReadMe.txt 70 | 71 | # StyleCop 72 | StyleCopReport.xml 73 | 74 | # Files built by Visual Studio 75 | *_i.c 76 | *_p.c 77 | *_h.h 78 | *.ilk 79 | *.meta 80 | *.obj 81 | *.iobj 82 | *.pch 83 | *.pdb 84 | *.ipdb 85 | *.pgc 86 | *.pgd 87 | *.rsp 88 | *.sbr 89 | *.tlb 90 | *.tli 91 | *.tlh 92 | *.tmp 93 | *.tmp_proj 94 | *_wpftmp.csproj 95 | *.log 96 | *.vspscc 97 | *.vssscc 98 | .builds 99 | *.pidb 100 | *.svclog 101 | *.scc 102 | 103 | # Chutzpah Test files 104 | _Chutzpah* 105 | 106 | # Visual C++ cache files 107 | ipch/ 108 | *.aps 109 | *.ncb 110 | *.opendb 111 | *.opensdf 112 | *.sdf 113 | *.cachefile 114 | *.VC.db 115 | *.VC.VC.opendb 116 | 117 | # Visual Studio profiler 118 | *.psess 119 | *.vsp 120 | *.vspx 121 | *.sap 122 | 123 | # Visual Studio Trace Files 124 | *.e2e 125 | 126 | # TFS 2012 Local Workspace 127 | $tf/ 128 | 129 | # Guidance Automation Toolkit 130 | *.gpState 131 | 132 | # ReSharper is a .NET coding add-in 133 | _ReSharper*/ 134 | *.[Rr]e[Ss]harper 135 | *.DotSettings.user 136 | 137 | # TeamCity is a build add-in 138 | _TeamCity* 139 | 140 | # DotCover is a Code Coverage Tool 141 | *.dotCover 142 | 143 | # AxoCover is a Code Coverage Tool 144 | .axoCover/* 145 | !.axoCover/settings.json 146 | 147 | # Coverlet is a free, cross platform Code Coverage Tool 148 | coverage*.json 149 | coverage*.xml 150 | coverage*.info 151 | 152 | # Visual Studio code coverage results 153 | *.coverage 154 | *.coveragexml 155 | 156 | # NCrunch 157 | _NCrunch_* 158 | .*crunch*.local.xml 159 | nCrunchTemp_* 160 | 161 | # MightyMoose 162 | *.mm.* 163 | AutoTest.Net/ 164 | 165 | # Web workbench (sass) 166 | .sass-cache/ 167 | 168 | # Installshield output folder 169 | [Ee]xpress/ 170 | 171 | # DocProject is a documentation generator add-in 172 | DocProject/buildhelp/ 173 | DocProject/Help/*.HxT 174 | DocProject/Help/*.HxC 175 | DocProject/Help/*.hhc 176 | DocProject/Help/*.hhk 177 | DocProject/Help/*.hhp 178 | DocProject/Help/Html2 179 | DocProject/Help/html 180 | 181 | # Click-Once directory 182 | publish/ 183 | 184 | # Publish Web Output 185 | *.[Pp]ublish.xml 186 | *.azurePubxml 187 | # Note: Comment the next line if you want to checkin your web deploy settings, 188 | # but database connection strings (with potential passwords) will be unencrypted 189 | *.pubxml 190 | *.publishproj 191 | 192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 193 | # checkin your Azure Web App publish settings, but sensitive information contained 194 | # in these scripts will be unencrypted 195 | PublishScripts/ 196 | 197 | # NuGet Packages 198 | *.nupkg 199 | # NuGet Symbol Packages 200 | *.snupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | *.appxbundle 226 | *.appxupload 227 | 228 | # Visual Studio cache files 229 | # files ending in .cache can be ignored 230 | *.[Cc]ache 231 | # but keep track of directories ending in .cache 232 | !?*.[Cc]ache/ 233 | 234 | # Others 235 | ClientBin/ 236 | ~$* 237 | *~ 238 | *.dbmdl 239 | *.dbproj.schemaview 240 | *.jfm 241 | *.pfx 242 | *.publishsettings 243 | orleans.codegen.cs 244 | 245 | # Including strong name files can present a security risk 246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 247 | #*.snk 248 | 249 | # Since there are multiple workflows, uncomment next line to ignore bower_components 250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 251 | #bower_components/ 252 | 253 | # RIA/Silverlight projects 254 | Generated_Code/ 255 | 256 | # Backup & report files from converting an old project file 257 | # to a newer Visual Studio version. Backup files are not needed, 258 | # because we have git ;-) 259 | _UpgradeReport_Files/ 260 | Backup*/ 261 | UpgradeLog*.XML 262 | UpgradeLog*.htm 263 | ServiceFabricBackup/ 264 | *.rptproj.bak 265 | 266 | # SQL Server files 267 | *.mdf 268 | *.ldf 269 | *.ndf 270 | 271 | # Business Intelligence projects 272 | *.rdl.data 273 | *.bim.layout 274 | *.bim_*.settings 275 | *.rptproj.rsuser 276 | *- [Bb]ackup.rdl 277 | *- [Bb]ackup ([0-9]).rdl 278 | *- [Bb]ackup ([0-9][0-9]).rdl 279 | 280 | # Microsoft Fakes 281 | FakesAssemblies/ 282 | 283 | # GhostDoc plugin setting file 284 | *.GhostDoc.xml 285 | 286 | # Node.js Tools for Visual Studio 287 | .ntvs_analysis.dat 288 | node_modules/ 289 | 290 | # Visual Studio 6 build log 291 | *.plg 292 | 293 | # Visual Studio 6 workspace options file 294 | *.opt 295 | 296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 297 | *.vbw 298 | 299 | # Visual Studio LightSwitch build output 300 | **/*.HTMLClient/GeneratedArtifacts 301 | **/*.DesktopClient/GeneratedArtifacts 302 | **/*.DesktopClient/ModelManifest.xml 303 | **/*.Server/GeneratedArtifacts 304 | **/*.Server/ModelManifest.xml 305 | _Pvt_Extensions 306 | 307 | # Paket dependency manager 308 | .paket/paket.exe 309 | paket-files/ 310 | 311 | # FAKE - F# Make 312 | .fake/ 313 | 314 | # CodeRush personal settings 315 | .cr/personal 316 | 317 | # Python Tools for Visual Studio (PTVS) 318 | __pycache__/ 319 | *.pyc 320 | 321 | # Cake - Uncomment if you are using it 322 | # tools/** 323 | # !tools/packages.config 324 | 325 | # Tabs Studio 326 | *.tss 327 | 328 | # Telerik's JustMock configuration file 329 | *.jmconfig 330 | 331 | # BizTalk build output 332 | *.btp.cs 333 | *.btm.cs 334 | *.odx.cs 335 | *.xsd.cs 336 | 337 | # OpenCover UI analysis results 338 | OpenCover/ 339 | 340 | # Azure Stream Analytics local run output 341 | ASALocalRun/ 342 | 343 | # MSBuild Binary and Structured Log 344 | *.binlog 345 | 346 | # NVidia Nsight GPU debugger configuration file 347 | *.nvuser 348 | 349 | # MFractors (Xamarin productivity tool) working folder 350 | .mfractor/ 351 | 352 | # Local History for Visual Studio 353 | .localhistory/ 354 | 355 | # BeatPulse healthcheck temp database 356 | healthchecksdb 357 | 358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 359 | MigrationBackup/ 360 | 361 | # Ionide (cross platform F# VS Code tools) working folder 362 | .ionide/ 363 | 364 | # Fody - auto-generated XML schema 365 | FodyWeavers.xsd 366 | 367 | ## 368 | ## Visual studio for Mac 369 | ## 370 | 371 | 372 | # globs 373 | Makefile.in 374 | *.userprefs 375 | *.usertasks 376 | config.make 377 | config.status 378 | aclocal.m4 379 | install-sh 380 | autom4te.cache/ 381 | *.tar.gz 382 | tarballs/ 383 | test-results/ 384 | 385 | # Mac bundle stuff 386 | *.dmg 387 | *.app 388 | 389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 390 | # General 391 | .DS_Store 392 | .AppleDouble 393 | .LSOverride 394 | 395 | # Icon must end with two \r 396 | Icon 397 | 398 | 399 | # Thumbnails 400 | ._* 401 | 402 | # Files that might appear in the root of a volume 403 | .DocumentRevisions-V100 404 | .fseventsd 405 | .Spotlight-V100 406 | .TemporaryItems 407 | .Trashes 408 | .VolumeIcon.icns 409 | .com.apple.timemachine.donotpresent 410 | 411 | # Directories potentially created on remote AFP share 412 | .AppleDB 413 | .AppleDesktop 414 | Network Trash Folder 415 | Temporary Items 416 | .apdisk 417 | 418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 419 | # Windows thumbnail cache files 420 | Thumbs.db 421 | ehthumbs.db 422 | ehthumbs_vista.db 423 | 424 | # Dump file 425 | *.stackdump 426 | 427 | # Folder config file 428 | [Dd]esktop.ini 429 | 430 | # Recycle Bin used on file shares 431 | $RECYCLE.BIN/ 432 | 433 | # Windows Installer files 434 | *.cab 435 | *.msi 436 | *.msix 437 | *.msm 438 | *.msp 439 | 440 | # Windows shortcuts 441 | *.lnk 442 | 443 | # JetBrains Rider 444 | .idea/ 445 | *.sln.iml 446 | 447 | ## 448 | ## Visual Studio Code 449 | ## 450 | .vscode/* 451 | !.vscode/settings.json 452 | !.vscode/tasks.json 453 | !.vscode/launch.json 454 | !.vscode/extensions.json 455 | 456 | ### 457 | ### Env files 458 | ### 459 | .env 460 | .env.local 461 | -------------------------------------------------------------------------------- /dotnet/Contact.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DotNetQuickStart 4 | { 5 | public class Contact 6 | { 7 | public string Name { get; set; } 8 | 9 | public string ObjectID { get; set; } 10 | 11 | public string Email { get; set; } 12 | 13 | public override string ToString() 14 | { 15 | return $"Name: {Name}, ObjectId: {ObjectID}"; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /dotnet/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | using McMaster.Extensions.CommandLineUtils; 5 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/csharp/?client=csharp 6 | using Algolia.Search.Clients; 7 | using Algolia.Search.Models.Search; 8 | using Algolia.Search.Models.Settings; 9 | using Algolia.Search.Models.Batch; 10 | using Algolia.Search.Models.Enums; 11 | using dotenv.net; 12 | 13 | namespace DotNetQuickStart 14 | { 15 | class Program { 16 | 17 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 18 | // and choose a name for your index. Add these environment variables to a `.env` file: 19 | // ALGOLIA_APP_ID, ALGOLIA_API_KEY, ALGOLIA_INDEX_NAME 20 | private static string _appId; 21 | private static string _apiKey; 22 | private static string _indexName; 23 | 24 | public static int Main(string[] args) 25 | { 26 | DotEnv.Load(); 27 | 28 | InitKeys(); 29 | 30 | var app = new CommandLineApplication 31 | { 32 | Name = "fake-npm", 33 | Description = "A fake version of the node package manager", 34 | }; 35 | 36 | app.OnExecute(() => 37 | { 38 | Console.WriteLine("Specify a sample to run. Ex: `dotenet run simple`"); 39 | return 1; 40 | }); 41 | 42 | app.Command("simple", configCmd => 43 | { 44 | configCmd.OnExecute(() => 45 | { 46 | // Start the API client 47 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 48 | SearchClient client = new SearchClient(_appId, _apiKey); 49 | 50 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 51 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 52 | SearchIndex index = client.InitIndex(_indexName); 53 | 54 | // Add new objects to the index 55 | // https://www.algolia.com/doc/api-reference/api-methods/add-objects/ 56 | List objs = new List(); 57 | objs.Add(new Contact{ObjectID = "1", Name = "Foo"}); 58 | var res = index.SaveObjects(objs); 59 | 60 | // Wait for the indexing task to complete 61 | // https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 62 | res.Wait(); 63 | 64 | // Search the index for "Fo" 65 | // https://www.algolia.com/doc/api-reference/api-methods/search/ 66 | var search = index.Search(new Query("Fo")); 67 | Console.WriteLine(search.Hits.ElementAt(0).ToString()); 68 | 69 | return 1; 70 | }); 71 | }); 72 | 73 | app.Command("indexing", configCmd => 74 | { 75 | configCmd.OnExecute(() => 76 | { 77 | // Initialize the client 78 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 79 | SearchClient client = new SearchClient(_appId, _apiKey); 80 | 81 | // Initialize an index 82 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 83 | SearchIndex index = client.InitIndex(_indexName); 84 | 85 | // We don't have any objects (yet) in our index 86 | var search = index.Search(new Query("")); 87 | Console.WriteLine("Current objects: [{0}]\n", string.Join(", ", search.Hits)); 88 | 89 | // Define some objects to add to our index 90 | // https://www.algolia.com/doc/api-client/methods/indexing/#object-and-record 91 | List objs = new List(); 92 | objs.Add(new Contact{ObjectID = "1", Name = "Foo"}); 93 | objs.Add(new Contact{ObjectID = "2", Name = "Bar"}); 94 | 95 | // Save Objects: Add mutliple new objects to an index. 96 | // https://www.algolia.com/doc/api-reference/api-methods/add-objects/?client=csharp 97 | Console.WriteLine("Save Objects - Adding multiple objects: [{0}]", string.Join(", ", objs)); 98 | index.SaveObjects(objs).Wait(); 99 | 100 | search = index.Search(new Query("")); 101 | Console.WriteLine("Current objects: [{0}]\n", string.Join(", ", search.Hits)); 102 | 103 | // Save Objects: Replace an existing object with an updated set of attributes. 104 | // https://www.algolia.com/doc/api-reference/api-methods/save-objects/?client=csharp 105 | Console.WriteLine("Save Objects - Replacing objects’s attributes on: {0}'", objs[0]); 106 | Contact changedContact = new Contact { 107 | Name = "FooBar", 108 | ObjectID = "1" 109 | }; 110 | index.SaveObject(changedContact).Wait(); 111 | 112 | search = index.Search(new Query("")); 113 | Console.WriteLine("Current objects: [{0}]\n", string.Join(", ", search.Hits)); 114 | 115 | // Partial Update Objects: Update one or more attributes of an existing object. 116 | // https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/?client=csharp 117 | Console.WriteLine("Save Objects - Updating object’s attributes on: {0}", objs[0]); 118 | Contact anotherChangedContact = new Contact{ 119 | Email = "foo@bar.com", 120 | ObjectID = "1" 121 | }; 122 | index.PartialUpdateObject(anotherChangedContact).Wait(); 123 | 124 | search = index.Search(new Query("")); 125 | Console.WriteLine("Current objects: [{0}]\n", string.Join(", ", search.Hits)); 126 | 127 | // Delete Objects: Remove objects from an index using their objectID. 128 | // https://www.algolia.com/doc/api-reference/api-methods/delete-objects/?client=csharp 129 | var objectIdToDelete = objs[0].ObjectID; 130 | Console.WriteLine("Delete Objects - Deleting object with objectID: \"{0}\"", objectIdToDelete); 131 | index.DeleteObject(objectIdToDelete).Wait(); 132 | 133 | search = index.Search(new Query("")); 134 | Console.WriteLine("Current objects: [{0}]\n", string.Join(", ", search.Hits)); 135 | 136 | // Replace All Objects: Clears all objects from your index and replaces them with a new set of objects. 137 | // https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/?client=csharp 138 | List newObjs = new List(); 139 | newObjs.Add(new Contact{ObjectID = "1", Name = "NewFoo"}); 140 | newObjs.Add(new Contact{ObjectID = "2", Name = "NewBar"}); 141 | Console.WriteLine("Replace All Objects - Clears all objects and replaces them with: [{0}]", string.Join(", ", newObjs)); 142 | index.ReplaceAllObjects(newObjs).Wait(); 143 | 144 | search = index.Search(new Query("")); 145 | Console.WriteLine("Current objects: [{0}]\n", string.Join(", ", search.Hits)); 146 | 147 | // Delete By: Remove all objects matching a filter (including geo filters). 148 | // https://www.algolia.com/doc/api-reference/api-methods/delete-by/?client=csharp 149 | Console.WriteLine("Delete By - Remove all objects matching \"name:NewBar\""); 150 | 151 | // Firstly, have an attribute to filter on 152 | // https://www.algolia.com/doc/api-client/methods/settings/?client=csharp 153 | index.SetSettings(new IndexSettings { 154 | AttributesForFaceting = new List{"name"} 155 | }).Wait(); 156 | 157 | index.DeleteBy(new Query { 158 | FacetFilters = new List>{ new List {"name:NewBar"} } // https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ 159 | }).Wait(); 160 | 161 | search = index.Search(new Query("")); 162 | Console.WriteLine("Current objects: [{0}]\n", string.Join(", ", search.Hits)); 163 | 164 | // Get Objects: Get one or more objects using their objectIDs. 165 | // https://www.algolia.com/doc/api-reference/api-methods/get-objects/?client=csharp 166 | var objectId = newObjs[0].ObjectID; 167 | Console.WriteLine("Get Objects - Getting object with objectID \"{0}\"", objectId); 168 | 169 | var contact = index.GetObject(objectId); 170 | Console.WriteLine("Result: \"{0}\"", contact); 171 | 172 | // Custom Batch: Perform several indexing operations in one API call. 173 | // https://www.algolia.com/doc/api-reference/api-methods/batch/?client=csharp 174 | List> operations = new List> 175 | { 176 | new BatchOperation 177 | { 178 | Action = BatchActionType.AddObject, 179 | IndexName = _indexName, 180 | Body = new Contact { Name = "BatchedBar" } 181 | }, 182 | new BatchOperation 183 | { 184 | Action = BatchActionType.UpdateObject, 185 | IndexName = _indexName, 186 | Body = new Contact { Name = "NewBatchedBar", ObjectID = objectId } 187 | } 188 | }; 189 | Console.WriteLine("Custom Batch - Batching {0} operations", operations.Count()); 190 | client.MultipleBatch(operations).Wait(); 191 | 192 | search = index.Search(new Query("")); 193 | Console.WriteLine("Current objects: [{0}]\n", string.Join(", ", search.Hits)); 194 | 195 | // Clear Objects: Clear the records of an index without affecting its settings. 196 | // https://www.algolia.com/doc/api-reference/api-methods/clear-objects/?client=csharp 197 | Console.WriteLine("Clear Objects: Clear the records of an index without affecting its settings."); 198 | index.ClearObjects().Wait(); 199 | 200 | // We don't have any objects in our index 201 | search = index.Search(new Query("")); 202 | Console.WriteLine("Current objects: [{0}]", string.Join(", ", search.Hits)); 203 | 204 | return 1; 205 | }); 206 | }); 207 | 208 | return app.Execute(args); 209 | } 210 | 211 | static void InitKeys() 212 | { 213 | if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ALGOLIA_APP_ID"))) 214 | { 215 | Console.WriteLine("Please set the following environment variable : ALGOLIA_APP_ID"); 216 | Environment.Exit(1); 217 | } 218 | 219 | if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ALGOLIA_API_KEY"))) 220 | { 221 | Console.WriteLine("Please set the following environment variable : ALGOLIA_API_KEY"); 222 | Environment.Exit(1); 223 | } 224 | 225 | if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ALGOLIA_INDEX_NAME"))) 226 | { 227 | Console.WriteLine("Please set the following environment variable : ALGOLIA_INDEX_NAME"); 228 | Environment.Exit(1); 229 | } 230 | 231 | _appId = Environment.GetEnvironmentVariable("ALGOLIA_APP_ID"); 232 | _apiKey = Environment.GetEnvironmentVariable("ALGOLIA_API_KEY"); 233 | _indexName = Environment.GetEnvironmentVariable("ALGOLIA_INDEX_NAME"); 234 | } 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /dotnet/README.md: -------------------------------------------------------------------------------- 1 | # API Clients Quickstarts: .NET 2 | 3 | This quickstart demonstrates various usages of the the [Algolia .NET API Client](https://www.algolia.com/doc/api-client/getting-started/install/csharp/?client=csharp). 4 | 5 | ## Setting up the quickstart 6 | 7 | ### Prerequisites 8 | 9 | - An Algolia account. If you don't have one already, [create an account for free](https://www.algolia.com/users/sign_up). 10 | - A [compatible .NET local environment](https://github.com/algolia/algoliasearch-client-csharp#-features), or [Docker](https://www.docker.com/get-started). 11 | 12 |
13 | Using VSCode 14 | 15 | By using VScode and having the [Visual Studio Code Remote - Containers](https://code.visualstudio.com/docs/remote/containers) extension installed, you can run any of the quickstarts by using the command [Remote-Containers: Open Folder in Container](https://code.visualstudio.com/docs/remote/containers#_quick-start-open-an-existing-folder-in-a-container) command. 16 | 17 | Each of the quickstart contains a [.devcontainer.json](./.devcontainer/devcontainer.json), along with a [Dockerfile](./.devcontainer/Dockerfile). 18 |
19 | 20 | 1. Create an Algolia Application and an [Algolia Index](https://www.algolia.com/doc/guides/getting-started/quick-start/tutorials/getting-started-with-the-dashboard/#indices) 21 | 2. Copy the file [.env.example](.env.example) and rename it to `.env` 22 | 3. Set the environment variables `ALGOLIA_APP_ID`, `ALGOLIA_API_KEY` and `ALGOLIA_INDEX_NAME` in the `.env` file. You can obtain those from the [Algolia Dashboard](https://www.algolia.com/api-keys/). The `ALGOLIA_API_KEY` should be the "Admin API Key" (necessary for indexing). 23 | 24 | ## How to use 25 | 26 | Once setup, you can run each of the sample in this folder using the .NET command line. 27 | Example: to execute the `simple` sample: 28 | 29 | ```bash 30 | dotnet run simple 31 | ``` 32 | 33 | ## Available quickstarts 34 | 35 | | File | Description | 36 | | ------------- | ------------- | 37 | | [simple](./Program.cs#37) | Index a single object and run a search query | 38 | | [indexing](./Program.cs#68) | Showcase of the main indexing methods | 39 | -------------------------------------------------------------------------------- /dotnet/dotnet.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /go/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] Go version (use -bullseye variants on local arm64/Apple Silicon): 1, 1.16, 1.17, 1-bullseye, 1.16-bullseye, 1.17-bullseye, 1-buster, 1.16-buster, 1.17-buster 2 | ARG VARIANT=1-bullseye 3 | FROM mcr.microsoft.com/vscode/devcontainers/go:0-${VARIANT} 4 | 5 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 6 | ARG NODE_VERSION="none" 7 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 8 | 9 | # [Optional] Uncomment this section to install additional OS packages. 10 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 11 | # && apt-get -y install --no-install-recommends 12 | 13 | # [Optional] Uncomment the next line to use go get to install anything else you need 14 | # RUN go get -x 15 | 16 | # [Optional] Uncomment this line to install global node packages. 17 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /go/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Go", 3 | "build": { 4 | "dockerfile": "Dockerfile", 5 | "args": { 6 | // Update the VARIANT arg to pick a version of Go: 1, 1.16, 1.17 7 | // Append -bullseye or -buster to pin to an OS version. 8 | // Use -bullseye variants on local arm64/Apple Silicon. 9 | "VARIANT": "1-bullseye", 10 | // Options 11 | "NODE_VERSION": "lts/*" 12 | } 13 | }, 14 | "runArgs": [ "--init", "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ], 15 | 16 | // Set *default* container specific settings.json values on container create. 17 | "settings": { 18 | "go.toolsManagement.checkForUpdates": "local", 19 | "go.useLanguageServer": true, 20 | "go.gopath": "/go", 21 | "go.goroot": "/usr/local/go" 22 | }, 23 | 24 | // Add the IDs of extensions you want installed when the container is created. 25 | "extensions": [ 26 | "golang.Go" 27 | ], 28 | 29 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 30 | // "forwardPorts": [], 31 | 32 | // Use 'postCreateCommand' to run commands after the container is created. 33 | // "postCreateCommand": "go version", 34 | 35 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 36 | "remoteUser": "vscode", 37 | "postStartCommand": "go mod tidy" 38 | } -------------------------------------------------------------------------------- /go/.env.example: -------------------------------------------------------------------------------- 1 | ALGOLIA_APP_ID= 2 | ALGOLIA_API_KEY= 3 | ALGOLIA_INDEX_NAME= -------------------------------------------------------------------------------- /go/README.md: -------------------------------------------------------------------------------- 1 | # API Clients Quickstarts: Go 2 | 3 | This quickstart demonstrates various usages of the the [Algolia Go API Client](https://www.algolia.com/doc/api-client/getting-started/install/go/?client=go). 4 | 5 | ## Setting up the quickstart 6 | 7 | ### Prerequisites 8 | 9 | - An Algolia account. If you don't have one already, [create an account for free](https://www.algolia.com/users/sign_up). 10 | - A Go >= 1.11 local environment, or [Docker](https://www.docker.com/get-started). 11 | 12 |
13 | Using VSCode 14 | 15 | By using VScode and having the [Visual Studio Code Remote - Containers](https://code.visualstudio.com/docs/remote/containers) extension installed, you can run any of the quickstarts by using the command [Remote-Containers: Open Folder in Container](https://code.visualstudio.com/docs/remote/containers#_quick-start-open-an-existing-folder-in-a-container) command. 16 | 17 | Each of the quickstart contains a [.devcontainer.json](./.devcontainer/devcontainer.json), along with a [Dockerfile](./.devcontainer/Dockerfile). 18 |
19 | 20 | 1. Create an Algolia Application and an [Algolia Index](https://www.algolia.com/doc/guides/getting-started/quick-start/tutorials/getting-started-with-the-dashboard/#indices) 21 | 2. Copy the file [.env.example](.env.example) and rename it to `.env` 22 | 3. Set the environment variables `ALGOLIA_APP_ID`, `ALGOLIA_API_KEY` and `ALGOLIA_INDEX_NAME` in the `.env` file. You can obtain those from the [Algolia Dashboard](https://www.algolia.com/api-keys/). The `ALGOLIA_API_KEY` should be the "Admin API Key" (necessary for indexing). 23 | 24 | 25 | ## How to use 26 | 27 | The module has two dependencies: 28 | * [Algolia GO API client](github.com/algolia/algoliasearch-client-go/v3) 29 | * [GoDotEnv](https://github.com/joho/godotenv) - for using environment variables 30 | 31 | Install these dependencies using the go build command. 32 | 33 | ```bash 34 | go build 35 | ``` 36 | Once setup, you can run each of the script in this folder using the Go command line. 37 | Example: to execute the `simple.go` script: 38 | 39 | ```bash 40 | go run simple.go 41 | ``` 42 | 43 | ## Available quickstarts 44 | 45 | | File | Description | 46 | | ------------- | ------------- | 47 | | [simple.go](./simple.go) | Index a single object and run a search query | 48 | | [indexing.go](./indexing.go) | Showcase of the main indexing methods | 49 | | [generate_key.go](./generate_key.go) | Generate a rate limted search API key | 50 | -------------------------------------------------------------------------------- /go/generate_key.go: -------------------------------------------------------------------------------- 1 | // generate_key creates an API key for an Algolia application. 2 | // The generated key will be valid for Search operations only, and is limited to 100 3 | // queries per hour. 4 | 5 | package main 6 | 7 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/go/?client=go 8 | import ( 9 | "errors" 10 | "fmt" 11 | "log" 12 | "os" 13 | 14 | "github.com/algolia/algoliasearch-client-go/v3/algolia/search" 15 | "github.com/joho/godotenv" 16 | ) 17 | 18 | func main() { 19 | var err error 20 | 21 | err = godotenv.Load() 22 | if err != nil { 23 | log.Fatal("Error loading .env file") 24 | } 25 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 26 | // and choose a name for your index. Add these environment variables to a `.env` file: 27 | appID, apiKey, indexName := os.Getenv("ALGOLIA_APP_ID"), os.Getenv("ALGOLIA_API_KEY"), os.Getenv("ALGOLIA_INDEX_NAME") 28 | 29 | // Start the API client 30 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 31 | client := search.NewClient(appID, apiKey) 32 | 33 | // Create the API key. 34 | // https://www.algolia.com/doc/api-reference/api-methods/add-api-key/?client=go 35 | fmt.Println("Generating key...") 36 | 37 | keyParams := search.Key{ 38 | ACL: []string{"search"}, 39 | Description: "Restricted search-only API key for algolia.com", 40 | MaxQueriesPerIPPerHour: 100, 41 | } 42 | 43 | var key string 44 | var keyRes search.CreateKeyRes 45 | 46 | keyRes, err = client.AddAPIKey(keyParams) 47 | err = keyRes.Wait() 48 | if err != nil { 49 | panic(errors.New("Error generating key.")) 50 | } else { 51 | key = keyRes.Key 52 | fmt.Println("Key generated successfully:", key) 53 | } 54 | 55 | // Test the new key 56 | fmt.Println("Testing key...") 57 | 58 | // Initialise a new client with the generated key 59 | client = search.NewClient(appID, key) 60 | 61 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 62 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 63 | index := client.InitIndex(indexName) 64 | 65 | // Search the index with an empty string 66 | // https://www.algolia.com/doc/api-reference/api-methods/search/ 67 | var indexRes search.QueryRes 68 | 69 | indexRes, err = index.Search("") 70 | if err != nil { 71 | panic(errors.New("Error testing key.")) 72 | } else { 73 | fmt.Println("Key tested successfully.", indexRes.NbHits, "hits found.") 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /go/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/algolia-samples/api-clients-quickstart 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/algolia/algoliasearch-client-go/v3 v3.4.0 7 | github.com/joho/godotenv v1.4.0 // indirect 8 | ) 9 | -------------------------------------------------------------------------------- /go/go.sum: -------------------------------------------------------------------------------- 1 | github.com/algolia/algoliasearch-client-go/v3 v3.4.0 h1:eeVU30L5DkKUK2q/EjXw+8o7reoK4QB1mS+BG0Jbd4Y= 2 | github.com/algolia/algoliasearch-client-go/v3 v3.4.0/go.mod h1:d0/D54BCmkwhLxT5VIQBeYLAz2GbZHFX9OptYyohTr0= 3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= 7 | github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= 8 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 9 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 10 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 11 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 12 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 13 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 14 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 15 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 16 | -------------------------------------------------------------------------------- /go/indexing.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | 8 | "github.com/algolia/algoliasearch-client-go/v3/algolia/opt" 9 | "github.com/algolia/algoliasearch-client-go/v3/algolia/search" 10 | "github.com/joho/godotenv" 11 | ) 12 | 13 | type Contact struct { 14 | ObjectID string `json:"objectID,omitempty"` 15 | Name string `json:"name,omitempty"` 16 | Email string `json:"email,omitempty"` 17 | } 18 | 19 | func PrintErrAndExit(err error) { 20 | fmt.Println(err) 21 | os.Exit(1) 22 | } 23 | 24 | func PrintCurrentObjects(i search.Index) { 25 | resSearch, err := i.Search("") 26 | if err != nil { 27 | PrintErrAndExit(err) 28 | } 29 | fmt.Println("Current objects: ", resSearch.Hits, "\n") 30 | } 31 | 32 | func main() { 33 | if err := godotenv.Load(); err != nil { 34 | log.Fatalf("godotenv.Load: %v", err) 35 | } 36 | 37 | // Algolia client credentials 38 | appID, apiKey, indexName := os.Getenv("ALGOLIA_APP_ID"), os.Getenv("ALGOLIA_API_KEY"), os.Getenv("ALGOLIA_INDEX_NAME") 39 | 40 | // Initialize the client 41 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 42 | client := search.NewClient(appID, apiKey) 43 | 44 | // Initialize an index 45 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 46 | index := client.InitIndex(indexName) 47 | 48 | // Define some objects to add to our index 49 | // https://www.algolia.com/doc/api-client/methods/indexing/#object-and-record 50 | contacts := []Contact{ 51 | { 52 | Name: "Foo", 53 | ObjectID: "1", 54 | }, 55 | { 56 | Name: "Bar", 57 | ObjectID: "2", 58 | }, 59 | } 60 | 61 | // We don't have any objects (yet) in our index 62 | PrintCurrentObjects(*index) 63 | 64 | // Save Objects: Add mutliple new objects to an index. 65 | // https://www.algolia.com/doc/api-reference/api-methods/add-objects/?client=go 66 | fmt.Println("Save Objects - Adding multiple objects: ", contacts) 67 | resSaveMultiple, err := index.SaveObjects(contacts) 68 | if err != nil { 69 | PrintErrAndExit(err) 70 | } 71 | err = resSaveMultiple.Wait() 72 | if err != nil { 73 | PrintErrAndExit(err) 74 | } 75 | PrintCurrentObjects(*index) 76 | 77 | // Save Objects: Replace an existing object with an updated set of attributes. 78 | // https://www.algolia.com/doc/api-reference/api-methods/save-objects/?client=go 79 | fmt.Println("Save Objects - Replacing objects’s attributes on:", contacts[0]) 80 | newContact := Contact{ 81 | Name: "FooBar", 82 | ObjectID: "1", 83 | } 84 | resSaveSingle, err := index.SaveObject(newContact) 85 | if err != nil { 86 | PrintErrAndExit(err) 87 | } 88 | err = resSaveSingle.Wait() 89 | if err != nil { 90 | PrintErrAndExit(err) 91 | } 92 | PrintCurrentObjects(*index) 93 | 94 | // Partial Update Objects: Update one or more attributes of an existing object. 95 | // https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/?client=go 96 | fmt.Println("Partial Update Objects - Updating object’s attributes on:", contacts[0]) 97 | newContact = Contact{ 98 | Email: "foo@bar.com", // New attribute 99 | ObjectID: "1", 100 | } 101 | resPartialUpdate, err := index.PartialUpdateObject(newContact) 102 | if err != nil { 103 | PrintErrAndExit(err) 104 | } 105 | err = resPartialUpdate.Wait() 106 | if err != nil { 107 | PrintErrAndExit(err) 108 | } 109 | PrintCurrentObjects(*index) 110 | 111 | // Delete Objects: Remove objects from an index using their objectID. 112 | // https://www.algolia.com/doc/api-reference/api-methods/delete-objects/?client=go 113 | objectIDToDelete := contacts[0].ObjectID 114 | fmt.Println("Delete Objects - Deleting object with objectID:", objectIDToDelete) 115 | resDelete, err := index.DeleteObject(objectIDToDelete) 116 | if err != nil { 117 | PrintErrAndExit(err) 118 | } 119 | err = resDelete.Wait() 120 | if err != nil { 121 | PrintErrAndExit(err) 122 | } 123 | PrintCurrentObjects(*index) 124 | 125 | // Replace All Objects: Clears all objects from your index and replaces them with a new set of objects. 126 | // https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/?client=go 127 | newContacts := []Contact{ 128 | { 129 | Name: "NewFoo", 130 | ObjectID: "3", 131 | }, 132 | { 133 | Name: "NewBar", 134 | ObjectID: "4", 135 | }, 136 | } 137 | fmt.Println("Replace All Objects - Clears all objects and replaces them with:", newContacts) 138 | resReplaceAll, err := index.ReplaceAllObjects(newContacts) 139 | if err != nil { 140 | PrintErrAndExit(err) 141 | } 142 | err = resReplaceAll.Wait() 143 | if err != nil { 144 | PrintErrAndExit(err) 145 | } 146 | PrintCurrentObjects(*index) 147 | 148 | // Delete By: Remove all objects matching a filter (including geo filters). 149 | // https://www.algolia.com/doc/api-reference/api-methods/delete-by/?client=go 150 | fmt.Println("Delete By - Remove all objects matching 'name:NewBar'") 151 | 152 | // Firstly, have an attribute to filter on 153 | // https://www.algolia.com/doc/api-client/methods/settings/?client=go 154 | resSetSettings, err := index.SetSettings(search.Settings{ 155 | AttributesForFaceting: opt.AttributesForFaceting("name"), 156 | }) 157 | if err != nil { 158 | PrintErrAndExit(err) 159 | } 160 | err = resSetSettings.Wait() 161 | if err != nil { 162 | PrintErrAndExit(err) 163 | } 164 | 165 | resDeleteBy, err := index.DeleteBy(opt.Filters("name:NewBar")) // https://www.algolia.com/doc/api-reference/api-parameters/filters/ 166 | if err != nil { 167 | PrintErrAndExit(err) 168 | } 169 | err = resDeleteBy.Wait() 170 | if err != nil { 171 | PrintErrAndExit(err) 172 | } 173 | PrintCurrentObjects(*index) 174 | 175 | // Get Objects: Get one or more objects using their objectIDs. 176 | // https://www.algolia.com/doc/api-reference/api-methods/get-objects/?client=go 177 | objectID := newContacts[0].ObjectID 178 | fmt.Println("Get Objects - Getting object with objectID:", objectID) 179 | 180 | var retrievedContact Contact 181 | err = index.GetObject(objectID, &retrievedContact) 182 | if err != nil { 183 | PrintErrAndExit(err) 184 | } 185 | fmt.Println("Results: ", retrievedContact) 186 | 187 | // Custom Batch: Perform several indexing operations in one API call. 188 | // https://www.algolia.com/doc/api-reference/api-methods/batch/?client=go 189 | operations := []search.BatchOperationIndexed{ 190 | { 191 | IndexName: indexName, 192 | BatchOperation: search.BatchOperation{ 193 | Action: search.AddObject, 194 | Body: Contact{ 195 | Name: "BatchedBar", 196 | }, 197 | }, 198 | }, 199 | { 200 | IndexName: indexName, 201 | BatchOperation: search.BatchOperation{ 202 | Action: search.UpdateObject, 203 | Body: Contact{ 204 | ObjectID: objectID, 205 | Name: "NewBatchedBar", 206 | }, 207 | }, 208 | }, 209 | } 210 | fmt.Println("Custom Batch - Batching operations:", operations) 211 | resBatch, err := client.MultipleBatch(operations) 212 | if err != nil { 213 | PrintErrAndExit(err) 214 | } 215 | err = resBatch.Wait() 216 | if err != nil { 217 | PrintErrAndExit(err) 218 | } 219 | PrintCurrentObjects(*index) 220 | 221 | // Clear Objects: Clear the records of an index without affecting its settings. 222 | // https://www.algolia.com/doc/api-reference/api-methods/clear-objects/?client=go 223 | fmt.Println("Clear Objects: Clear the records of an index without affecting its settings.") 224 | resClear, err := index.ClearObjects() 225 | if err != nil { 226 | PrintErrAndExit(err) 227 | } 228 | err = resClear.Wait() 229 | if err != nil { 230 | PrintErrAndExit(err) 231 | } 232 | PrintCurrentObjects(*index) 233 | } 234 | -------------------------------------------------------------------------------- /go/simple.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/go/?client=go 4 | import ( 5 | "fmt" 6 | "os" 7 | "github.com/algolia/algoliasearch-client-go/v3/algolia/search" 8 | "github.com/joho/godotenv" 9 | "log" 10 | ) 11 | 12 | type Contact struct { 13 | ObjectID string `json:"objectID"` 14 | Name string `json:"name"` 15 | } 16 | 17 | func main() { 18 | err := godotenv.Load() 19 | if err != nil { 20 | log.Fatal("Error loading .env file") 21 | } 22 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 23 | // and choose a name for your index. Add these environment variables to a `.env` file: 24 | appID, apiKey, indexName := os.Getenv("ALGOLIA_APP_ID"), os.Getenv("ALGOLIA_API_KEY"), os.Getenv("ALGOLIA_INDEX_NAME") 25 | 26 | // Start the API client 27 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 28 | client := search.NewClient(appID, apiKey) 29 | 30 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 31 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 32 | index := client.InitIndex(indexName) 33 | 34 | // Add new objects to the index 35 | // https://www.algolia.com/doc/api-reference/api-methods/add-objects/ 36 | resSave, err := index.SaveObjects([]Contact{ 37 | {ObjectID: "1", Name: "Foo"}, 38 | }) 39 | if err != nil { 40 | fmt.Println(err) 41 | os.Exit(1) 42 | } 43 | 44 | // Wait for the indexing task to complete 45 | // https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 46 | err = resSave.Wait() 47 | if err != nil { 48 | fmt.Println(err) 49 | os.Exit(1) 50 | } 51 | 52 | // Search the index for "Fo" 53 | // https://www.algolia.com/doc/api-reference/api-methods/search/ 54 | res, err := index.Search("Foo") 55 | if err != nil { 56 | fmt.Println(err) 57 | os.Exit(1) 58 | } 59 | 60 | var contacts []Contact 61 | 62 | err = res.UnmarshalHits(&contacts) 63 | if err != nil { 64 | fmt.Println(err) 65 | os.Exit(1) 66 | } 67 | 68 | fmt.Println("search results: ", contacts) 69 | } 70 | -------------------------------------------------------------------------------- /java/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] Java version (use -bullseye variants on local arm64/Apple Silicon): 11, 16, 11-bullseye, 16-bullseye, 11-buster, 17-buster 2 | ARG VARIANT=11-bullseye 3 | FROM mcr.microsoft.com/vscode/devcontainers/java:${VARIANT} 4 | 5 | # [Option] Install Maven 6 | ARG INSTALL_MAVEN="false" 7 | ARG MAVEN_VERSION="" 8 | # [Option] Install Gradle 9 | ARG INSTALL_GRADLE="false" 10 | ARG GRADLE_VERSION="" 11 | RUN if [ "${INSTALL_MAVEN}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install maven \"${MAVEN_VERSION}\""; fi \ 12 | && if [ "${INSTALL_GRADLE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install gradle \"${GRADLE_VERSION}\""; fi 13 | 14 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 15 | ARG NODE_VERSION="none" 16 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 17 | 18 | # [Optional] Uncomment this section to install additional OS packages. 19 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 20 | # && apt-get -y install --no-install-recommends 21 | 22 | # [Optional] Uncomment this line to install global node packages. 23 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /java/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Java", 3 | "runArgs": ["--init"], 4 | "build": { 5 | "dockerfile": "Dockerfile", 6 | "args": { 7 | // Update the VARIANT arg to pick a Java version: 11, 16 8 | // Append -bullseye or -buster to pin to an OS version. 9 | // Use the -bullseye variants on local arm64/Apple Silicon. 10 | "VARIANT": "11-jdk-bullseye", 11 | // Options 12 | "INSTALL_MAVEN": "true", 13 | "INSTALL_GRADLE": "false", 14 | "NODE_VERSION": "lts/*" 15 | } 16 | }, 17 | 18 | // Set *default* container specific settings.json values on container create. 19 | "settings": { 20 | "java.home": "/docker-java-home" 21 | }, 22 | 23 | // Add the IDs of extensions you want installed when the container is created. 24 | "extensions": [ 25 | "vscjava.vscode-java-pack" 26 | ], 27 | 28 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 29 | // "forwardPorts": [], 30 | 31 | // Use 'postCreateCommand' to run commands after the container is created. 32 | // "postCreateCommand": "java -version", 33 | 34 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 35 | "remoteUser": "vscode" 36 | } -------------------------------------------------------------------------------- /java/.env.example: -------------------------------------------------------------------------------- 1 | ALGOLIA_APP_ID= 2 | ALGOLIA_API_KEY= 3 | ALGOLIA_INDEX_NAME= -------------------------------------------------------------------------------- /java/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.configuration.updateBuildConfiguration": "automatic" 3 | } -------------------------------------------------------------------------------- /java/README.md: -------------------------------------------------------------------------------- 1 | # API Clients Quickstarts: Java 2 | 3 | This quickstart demonstrates various usages of the [Algolia Java API Client](https://www.algolia.com/doc/api-client/getting-started/install/java/?client=java). 4 | 5 | ## Setting up the quickstart 6 | 7 | ### Prerequisites 8 | 9 | - An Algolia account. If you don't have one already, [create an account for free](https://www.algolia.com/users/sign_up). 10 | - A Java local environment, or [Docker](https://www.docker.com/get-started). 11 | 12 |
13 | Using VSCode 14 | 15 | By using VScode and having the [Visual Studio Code Remote - Containers](https://code.visualstudio.com/docs/remote/containers) extension installed, you can run any of the quickstarts by using the command [Remote-Containers: Open Folder in Container](https://code.visualstudio.com/docs/remote/containers#_quick-start-open-an-existing-folder-in-a-container) command. 16 | 17 | Each of the quickstart contains a [.devcontainer.json](./.devcontainer/devcontainer.json), along with a [Dockerfile](./.devcontainer/Dockerfile). 18 | 19 |
20 | 21 | 1. Create an Algolia Application and an [Algolia Index](https://www.algolia.com/doc/guides/getting-started/quick-start/tutorials/getting-started-with-the-dashboard/#indices) 22 | 2. Copy the file [.env.example](.env.example) and rename it to `.env` 23 | 3. Set the environment variables `ALGOLIA_APP_ID`, `ALGOLIA_API_KEY` and `ALGOLIA_INDEX_NAME` in the `.env` file. You can obtain those from the [Algolia Dashboard](https://www.algolia.com/api-keys/). The `ALGOLIA_API_KEY` should be the "Admin API Key" (necessary for indexing). 24 | 25 | ## How to use 26 | 27 | Once setup, you can run each of the script in this folder using your favorite Java IDE. 28 | 29 | ## Available quickstarts 30 | 31 | 32 | | File | Description | 33 | | ---------------------------- | -------------------------------------------- | 34 | | [Simple.java](./src/main/java/Simple.java) | Index a single object and run a search query | 35 | | [Indexing.java](./src/main/java/Indexing.java) | Showcase of the main indexing methods | 36 | -------------------------------------------------------------------------------- /java/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.algolia 8 | java-playground 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | org.apache.maven.plugins 14 | maven-compiler-plugin 15 | 16 | 8 17 | 8 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | com.algolia 26 | algoliasearch-core 27 | 3.0.0 28 | 29 | 30 | 31 | com.algolia 32 | algoliasearch-apache 33 | 3.0.0 34 | 35 | 36 | 37 | org.asynchttpclient 38 | async-http-client 39 | 2.8.1 40 | 41 | 42 | 43 | io.github.cdimascio 44 | dotenv-java 45 | 2.2.0 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /java/src/main/java/Contact.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | import java.util.Optional; 3 | 4 | public class Contact implements Serializable { 5 | 6 | public Contact() {} 7 | 8 | public Contact(String objectID, String name, Optional email) { 9 | this.objectID = objectID; 10 | this.name = name; 11 | this.email = email.orElse(""); 12 | } 13 | 14 | public String toString() { 15 | return String.format("", this.objectID, this.name); 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public Contact setName(String name) { 23 | this.name = name; 24 | return this; 25 | } 26 | 27 | public String getEmail() { 28 | return email; 29 | } 30 | 31 | public Contact setEmail(String email) { 32 | this.email = email; 33 | return this; 34 | } 35 | 36 | public String getObjectID() { 37 | return objectID; 38 | } 39 | 40 | public String getQueryID() { 41 | return queryID; 42 | } 43 | 44 | public Contact setQueryID(String queryID) { 45 | this.queryID = queryID; 46 | return this; 47 | } 48 | 49 | private String name; 50 | private String email; 51 | private String queryID; 52 | private String objectID; 53 | } -------------------------------------------------------------------------------- /java/src/main/java/Indexing.java: -------------------------------------------------------------------------------- 1 | import com.algolia.search.*; 2 | import com.algolia.search.models.indexing.BatchIndexingResponse; 3 | import com.algolia.search.models.indexing.Query; 4 | import com.algolia.search.models.indexing.SearchResult; 5 | import com.algolia.search.models.settings.IndexSettings; 6 | import com.algolia.search.models.indexing.BatchOperation; 7 | import com.algolia.search.models.indexing.BatchRequest; 8 | import com.algolia.search.models.indexing.ActionEnum; 9 | 10 | import java.io.IOException; 11 | import java.lang.StackWalker.Option; 12 | import java.util.List; 13 | import java.util.Arrays; 14 | import java.util.Optional; 15 | import java.util.concurrent.CompletableFuture; 16 | import java.util.concurrent.ExecutionException; 17 | import io.github.cdimascio.dotenv.Dotenv; 18 | 19 | public class Indexing { 20 | 21 | public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { 22 | Indexing.run(); 23 | } 24 | 25 | public static void run() throws ExecutionException, InterruptedException, IOException { 26 | 27 | Dotenv dotenv = Dotenv.configure().load(); 28 | 29 | // Start the API client 30 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 31 | try (SearchClient searchClient = 32 | DefaultSearchClient.create(dotenv.get("ALGOLIA_APP_ID"), dotenv.get("ALGOLIA_API_KEY"))) { 33 | 34 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 35 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 36 | SearchIndex index = searchClient.initIndex(dotenv.get("ALGOLIA_INDEX_NAME"), Contact.class); 37 | 38 | // Define some objects to add to our index 39 | // https://www.algolia.com/doc/api-client/methods/indexing/#object-and-record 40 | List contacts = Arrays.asList( 41 | new Contact("1", "Foo", Optional.empty()), 42 | new Contact("2", "Bar", Optional.empty()) 43 | ); 44 | 45 | // We don't have any objects (yet) in our index 46 | SearchResult searchResults = index.search(new Query("")); 47 | System.out.println("Current objects: " + searchResults.getHits()); 48 | 49 | // Save Objects: Add mutliple new objects to an index. 50 | // https://www.algolia.com/doc/api-reference/api-methods/add-objects/?client=java 51 | System.out.println("Save Objects - Adding multiple objects: " + contacts); 52 | index.saveObjects(contacts, true).waitTask(); 53 | 54 | searchResults = index.search(new Query("")); 55 | System.out.println("Current objects: " + searchResults.getHits()); 56 | 57 | // Save Objects: Replace an existing object with an updated set of attributes. 58 | // https://www.algolia.com/doc/api-reference/api-methods/save-objects/?client=java 59 | System.out.println("Save Objects - Replacing objects’s attributes on: " + contacts.get(0)); 60 | Contact firstContact = contacts.get(0).setName("FooBar"); 61 | index.saveObject(firstContact).waitTask(); 62 | 63 | searchResults = index.search(new Query("")); 64 | System.out.println("Current objects: " + searchResults.getHits()); 65 | 66 | // Partial Update Objects: Update one or more attributes of an existing object. 67 | // https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/?client=java 68 | System.out.println("Save Objects - Updating object’s attributes on: " + contacts.get(0)); 69 | firstContact.setEmail("test@test.com"); 70 | index.partialUpdateObject(firstContact).waitTask(); 71 | 72 | searchResults = index.search(new Query("")); 73 | System.out.println("Current objects: " + searchResults.getHits()); 74 | 75 | // Delete Objects: Remove objects from an index using their objectID. 76 | // https://www.algolia.com/doc/api-reference/api-methods/delete-objects/?client=java 77 | String objectIDToDelete = contacts.get(0).getObjectID(); 78 | System.out.println("Delete Objects - Deleting object with objectID: " + objectIDToDelete); 79 | index.deleteObject(objectIDToDelete).waitTask(); 80 | 81 | searchResults = index.search(new Query("")); 82 | System.out.println("Current objects: " + searchResults.getHits()); 83 | 84 | // Replace All Objects: Clears all objects from your index and replaces them with a new set of objects. 85 | // https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/?client=java 86 | List newContacts = Arrays.asList( 87 | new Contact("3", "NewFoo", Optional.empty()), 88 | new Contact("4", "NewBar", Optional.empty()) 89 | ); 90 | System.out.println("Replace All Objects - Clears all objects and replaces them with: " + newContacts); 91 | index.replaceAllObjects(newContacts, true); 92 | 93 | searchResults = index.search(new Query("")); 94 | System.out.println("Current objects: " + searchResults.getHits()); 95 | 96 | // Delete By: Remove all objects matching a filter (including geo filters). 97 | // https://www.algolia.com/doc/api-reference/api-methods/delete-by/?client=java 98 | System.out.println("Delete By - Remove all objects matching 'name:NewBar'"); 99 | 100 | // Firstly, have an attribute to filter on 101 | // https://www.algolia.com/doc/api-client/methods/settings/?client=java 102 | IndexSettings settings = new IndexSettings(); 103 | settings.setAttributesForFaceting(Arrays.asList("name")); 104 | index.setSettings(settings).waitTask(); 105 | 106 | // Now delete the records matching "name=NewBar" 107 | index.deleteBy(new Query("").setFacetFilters(Arrays.asList(Arrays.asList("name:NewBar")))); 108 | 109 | searchResults = index.search(new Query("")); 110 | System.out.println("Current objects: " + searchResults.getHits()); 111 | 112 | // Get Objects: Get one or more objects using their objectIDs. 113 | // https://www.algolia.com/doc/api-reference/api-methods/get-objects/?client=java 114 | String objectIDToRetrieve = newContacts.get(0).getObjectID(); 115 | System.out.println("Get Objects - Getting object with objectID: " + objectIDToRetrieve); 116 | 117 | Contact contact = index.getObject(objectIDToRetrieve); 118 | System.out.println("Result: " + contact); 119 | 120 | // Custom Batch: Perform several indexing operations in one API call. 121 | // https://www.algolia.com/doc/api-reference/api-methods/batch/?client=java 122 | List> operations = Arrays.asList( 123 | new BatchOperation<>(dotenv.get("ALGOLIA_INDEX_NAME"), ActionEnum.ADD_OBJECT, new Contact("3", "BatchedBar", Optional.empty())), 124 | new BatchOperation<>(dotenv.get("ALGOLIA_INDEX_NAME"), ActionEnum.UPDATE_OBJECT, new Contact("4", "BatchedFoo", Optional.empty())) 125 | ); 126 | System.out.println("Custom Batch"); 127 | searchClient.multipleBatch(operations).waitTask(); 128 | 129 | searchResults = index.search(new Query("")); 130 | System.out.println("Current objects: " + searchResults.getHits()); 131 | 132 | // Clear Objects: Clear the records of an index without affecting its settings. 133 | // https://www.algolia.com/doc/api-reference/api-methods/clear-objects/?client=java 134 | System.out.println("Clear objects"); 135 | index.clearObjects().waitTask(); 136 | 137 | searchResults = index.search(new Query("")); 138 | System.out.println("Current objects: " + searchResults.getHits()); 139 | } 140 | } 141 | } -------------------------------------------------------------------------------- /java/src/main/java/Simple.java: -------------------------------------------------------------------------------- 1 | import com.algolia.search.*; 2 | import com.algolia.search.models.indexing.BatchIndexingResponse; 3 | import com.algolia.search.models.indexing.Query; 4 | import com.algolia.search.models.indexing.SearchResult; 5 | import java.io.IOException; 6 | import java.util.concurrent.CompletableFuture; 7 | import java.util.concurrent.ExecutionException; 8 | import io.github.cdimascio.dotenv.Dotenv; 9 | 10 | public class Simple { 11 | 12 | public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { 13 | Simple.run(); 14 | } 15 | 16 | public static void run() throws ExecutionException, InterruptedException, IOException { 17 | 18 | Dotenv dotenv = Dotenv.configure().load(); 19 | 20 | // Start the API client 21 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 22 | try (SearchClient searchClient = 23 | DefaultSearchClient.create(dotenv.get("ALGOLIA_APP_ID"), dotenv.get("ALGOLIA_API_KEY"))) { 24 | 25 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 26 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 27 | SearchIndex index = searchClient.initIndex(dotenv.get("ALGOLIA_INDEX_NAME"), Contact.class); 28 | 29 | // Add new objects to the index 30 | // https://www.algolia.com/doc/api-reference/api-methods/add-objects/ 31 | Contact contact = new Contact("1", "Foo", null); 32 | CompletableFuture indexingFuture = index.saveObjectAsync(contact, true); 33 | 34 | // Wait for the indexing task to complete 35 | // https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 36 | indexingFuture.get(); 37 | 38 | // Search the index for "Fo" 39 | // https://www.algolia.com/doc/api-reference/api-methods/search/ 40 | CompletableFuture> searchAlgoliaFuture = 41 | index.searchAsync(new Query("Foo")); 42 | 43 | System.out.println("Search results:" + searchAlgoliaFuture.get().getHits()); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /javascript/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] Node.js version (use -bullseye variants on local arm64/Apple Silicon): 16, 14, 12, 16-bullseye, 14-bullseye, 12-bullseye, 16-buster, 14-buster, 12-buster 2 | ARG VARIANT=16-bullseye 3 | FROM mcr.microsoft.com/vscode/devcontainers/javascript-node:${VARIANT} 4 | 5 | # [Optional] Uncomment this section to install additional OS packages. 6 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 7 | # && apt-get -y install --no-install-recommends 8 | 9 | # [Optional] Uncomment if you want to install an additional version of node using nvm 10 | # ARG EXTRA_NODE_VERSION=10 11 | # RUN su node -c "source /usr/local/share/nvm/nvm.sh && nvm install ${EXTRA_NODE_VERSION}" 12 | 13 | # [Optional] Uncomment if you want to install more global node modules 14 | # RUN su node -c "npm install -g " -------------------------------------------------------------------------------- /javascript/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Node.js", 3 | "runArgs": ["--init"], 4 | "build": { 5 | "dockerfile": "Dockerfile", 6 | // Update 'VARIANT' to pick a Node version: 16, 14, 12. 7 | // Append -bullseye or -buster to pin to an OS version. 8 | // Use -bullseye variants on local arm64/Apple Silicon. 9 | "args": { "VARIANT": "16-bullseye" } 10 | }, 11 | 12 | // Set *default* container specific settings.json values on container create. 13 | "settings": {}, 14 | 15 | // Add the IDs of extensions you want installed when the container is created. 16 | "extensions": [ 17 | "dbaeumer.vscode-eslint" 18 | ], 19 | 20 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 21 | // "forwardPorts": [], 22 | 23 | // Use 'postCreateCommand' to run commands after the container is created. 24 | // "postCreateCommand": "yarn install", 25 | 26 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 27 | "remoteUser": "node", 28 | "postStartCommand": "yarn install" 29 | } -------------------------------------------------------------------------------- /javascript/.env.example: -------------------------------------------------------------------------------- 1 | ALGOLIA_APP_ID= 2 | ALGOLIA_API_KEY= 3 | ALGOLIA_INDEX_NAME= 4 | URL_DOMAIN= -------------------------------------------------------------------------------- /javascript/README.md: -------------------------------------------------------------------------------- 1 | # API Clients Quickstarts: JavaScript 2 | 3 | This quickstart demonstrates various usages of the [Algolia JavaScript API Client](https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript). 4 | 5 | ## Setting up the quickstart 6 | 7 | ### Prerequisites 8 | 9 | - An Algolia account. If you don't have one already, [create an account for free](https://www.algolia.com/users/sign_up). 10 | - A Node local environment, or [Docker](https://www.docker.com/get-started). 11 | 12 |
13 | Using VSCode 14 | 15 | By using VScode and having the [Visual Studio Code Remote - Containers](https://code.visualstudio.com/docs/remote/containers) extension installed, you can run any of the quickstarts by using the command [Remote-Containers: Open Folder in Container](https://code.visualstudio.com/docs/remote/containers#_quick-start-open-an-existing-folder-in-a-container) command. 16 | 17 | Each of the quickstart contains a [.devcontainer.json](./.devcontainer/devcontainer.json), along with a [Dockerfile](./.devcontainer/Dockerfile). 18 | 19 |
20 | 21 | 1. Create an Algolia Application and an [Algolia Index](https://www.algolia.com/doc/guides/getting-started/quick-start/tutorials/getting-started-with-the-dashboard/#indices) 22 | 2. Copy the file [.env.example](.env.example) and rename it to `.env` 23 | 3. Set the environment variables `ALGOLIA_APP_ID`, `ALGOLIA_API_KEY` and `ALGOLIA_INDEX_NAME` in the `.env` file. You can obtain those from the [Algolia Dashboard](https://www.algolia.com/api-keys/). The `ALGOLIA_API_KEY` should be the "Admin API Key" (necessary for indexing). 24 | 25 | ## How to use 26 | 27 | Once setup, you can run each of the script in this folder using the Node command line. 28 | Example: to execute the `simple.js` script: 29 | 30 | ```bash 31 | node simple.js 32 | ``` 33 | 34 | ## Available quickstarts 35 | 36 | 37 | | File | Description | 38 | 39 | | ---------------------------- | -------------------------------------------- | 40 | 41 | | [simple.js](./simple.js) | Index a single object and run a search query | 42 | 43 | | [indexing.js](./indexing.js) | Showcase of the main indexing methods | 44 | 45 | | [generate_key.js](./generate_key.js) | Generate a rate-limited search only API key | 46 | 47 | | [export_and_add_rule_to_index.js](./export_and_add_rule_to_index.js) | Export and add Rules to index | 48 | 49 | | [change_index_settings.js](./change_index_settings.js) | Change index settings | 50 | 51 | | [rest_API_return_top_1000_hits.js](./rest_API_return_top_1000_hits.js) | Return Top 1000 Searches | 52 | 53 | | [backup_index.js](./backup_index.js) | Generates a backup of records, settings, synonyms and rules in separate JSON files | 54 | 55 | | [restore_index.js](./restore_index.js) | Allows user to restore a backup of records, settings, synonyms and rules to an index | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /javascript/backup_index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Backup Index 3 | This script will export an index, including records, settings, rules and synonyms to the current directory. 4 | It can be used in conjunction with restore.js to backup and restore an index to an application. 5 | */ 6 | 7 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript 8 | const algoliasearch = require("algoliasearch"); 9 | const dotenv = require("dotenv"); 10 | 11 | dotenv.config(); 12 | 13 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 14 | // and choose a name for your index. Add these environment variables to a `.env` file: 15 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 16 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 17 | const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME; 18 | 19 | // Start the API client 20 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 21 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 22 | 23 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 24 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 25 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 26 | 27 | // Requiring fs module in which writeFile function is defined. 28 | const fs = require("fs"); 29 | 30 | let records = [], 31 | settings = [], 32 | rules = [], 33 | synonyms = []; 34 | 35 | (async () => { 36 | // retrieve all records from index 37 | console.log(`Retrieving records...`); 38 | try { 39 | await index.browseObjects({ 40 | batch: (batch) => { 41 | records = records.concat(batch); 42 | } 43 | }); 44 | 45 | console.log(`${records.length} records retrieved`); 46 | 47 | console.log(`Retrieving settings...`); 48 | 49 | // retrieve all index settings 50 | settings = await index.getSettings().then(); 51 | 52 | console.log(`settings retrieved`); 53 | 54 | console.log(`Retrieving rules...`); 55 | 56 | // retrieve all rules for index 57 | await index 58 | .browseRules({ 59 | batch: (batch) => { 60 | rules = rules.concat(batch); 61 | } 62 | }); 63 | 64 | console.log(`${rules.length} rules retrieved`); 65 | 66 | console.log(`Retrieving synonyms...`); 67 | 68 | // retrieve all synonyms for index 69 | await index 70 | .browseSynonyms({ 71 | batch: (batch) => { 72 | synonyms = synonyms.concat(batch); 73 | }, 74 | }); 75 | 76 | console.log(`${synonyms.length} synonyms retrieved`); 77 | } catch (error) { 78 | console.log(`Error retrieving data ${error.message}`); 79 | } 80 | 81 | // write json files to current directory 82 | function createJson(data, name) { 83 | if (data) { 84 | fs.writeFile( 85 | `${ALGOLIA_INDEX_NAME}_${name}.json`, 86 | JSON.stringify(data), 87 | (err) => { 88 | if (err) throw err; 89 | } 90 | ); 91 | } else 92 | (error) => { 93 | console.log(`Error writing files: ${error.message}`); 94 | }; 95 | } 96 | try { 97 | let name = "records"; 98 | createJson(records, name); 99 | name = "settings"; 100 | createJson(settings, name); 101 | name = "rules"; 102 | createJson(rules, name); 103 | name = "synonyms"; 104 | createJson(synonyms, name); 105 | } catch (error) { 106 | console.log(`Error exporting data ${error.message}`); 107 | } 108 | })(); 109 | -------------------------------------------------------------------------------- /javascript/change_index_settings.js: -------------------------------------------------------------------------------- 1 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript 2 | const algoliasearch = require("algoliasearch"); 3 | const dotenv = require("dotenv"); 4 | 5 | dotenv.config(); 6 | 7 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 8 | // and choose a name for your index. Add these environment variables to a `.env` file: 9 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 10 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 11 | const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME; 12 | 13 | // Start the API client 14 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 15 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 16 | 17 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 18 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 19 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 20 | 21 | // Changes an index's settings, Only specified settings are overridden; unspecified settings are left unchanged 22 | // https://www.algolia.com/doc/api-reference/api-methods/set-settings/#about-this-method 23 | index 24 | .setSettings({ 25 | searchableAttributes: ["name", "city"], 26 | customRanking: ["desc(followers)"], 27 | }, { 28 | // Option to forward the same settings to the replica indices. 29 | forwardToReplicas: true 30 | }) 31 | // Wait for the indexing task to complete 32 | // https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 33 | .wait() 34 | .then((response) => { 35 | // Display response (updatedAt, taskID) 36 | console.log(response); 37 | // Display both changed settings 38 | index.getSettings().then((settings) => { 39 | console.log(settings["searchableAttributes"], settings["customRanking"]); 40 | }); 41 | }) 42 | .catch((error) => console.log(error)); 43 | -------------------------------------------------------------------------------- /javascript/export_and_add_rule_to_index.js: -------------------------------------------------------------------------------- 1 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript 2 | const algoliasearch = require("algoliasearch"); 3 | const dotenv = require("dotenv"); 4 | // Requiring fs module in which writeFile function is defined. 5 | const fs = require("fs"); 6 | 7 | dotenv.config(); 8 | 9 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 10 | // and choose a name for your index. Add these environment variables to a `.env` file: 11 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 12 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 13 | const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME; 14 | 15 | // Start the API client 16 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 17 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 18 | 19 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 20 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 21 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 22 | 23 | // Export Rules for this index 24 | // https://www.algolia.com/doc/api-reference/api-methods/export-rules/ 25 | index 26 | .browseRules({ 27 | // A `batch` callback function that's called on every batch of rules 28 | batch: (batch) => 29 | // Export JSON file containing Rules into same directory with prefix of index_name 30 | fs.writeFile( 31 | `${ALGOLIA_INDEX_NAME}_rules.json`, 32 | JSON.stringify(batch), 33 | (err) => { 34 | // In case of a error throw err. 35 | if (err) throw err; 36 | } 37 | ), 38 | }) 39 | .then((response) => { 40 | // Success message 41 | console.log( 42 | `Rules saved as ${ALGOLIA_INDEX_NAME}_rules.json in the current directory` 43 | ); 44 | }) 45 | .catch((error) => console.log(error)); 46 | 47 | // Create a rule 48 | const rule = { 49 | objectID: "a-rule-id", 50 | conditions: [ 51 | { 52 | pattern: "Jimmie", 53 | anchoring: "is", 54 | }, 55 | ], 56 | consequence: { 57 | params: { 58 | filters: "zip_code = 12345", 59 | }, 60 | }, 61 | 62 | // Optionally, to disable the rule change to 'false' 63 | enabled: true, 64 | 65 | // Optionally, to add valitidy time ranges 66 | validity: [ 67 | { 68 | from: Math.floor(Date.now() / 1000), 69 | until: Math.floor(Date.now() / 1000) + 10 * 24 * 60 * 60, 70 | }, 71 | ], 72 | }; 73 | 74 | // Save the Rule. 75 | index.saveRule(rule).then(() => { 76 | // done 77 | }); 78 | 79 | // Save the Rule, and forward it to all replicas of the index. 80 | index.saveRule(rule, { forwardToReplicas: true }).then(() => { 81 | // done 82 | }); 83 | -------------------------------------------------------------------------------- /javascript/generate_key.js: -------------------------------------------------------------------------------- 1 | /* 2 | API Key Generator 3 | This script will generate an API key for an Algolia application. 4 | The generated key will be valid for Search operations, and will be limited to 100 queries per hour. 5 | */ 6 | 7 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript 8 | const algoliasearch = require("algoliasearch"); 9 | const dotenv = require("dotenv"); 10 | 11 | dotenv.config(); 12 | 13 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 14 | // and choose a name for your index. Add these environment variables to a `.env` file: 15 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 16 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 17 | const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME; 18 | 19 | // Start the API client 20 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 21 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 22 | 23 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 24 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 25 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 26 | 27 | // Set permissions for API key 28 | // https://www.algolia.com/doc/api-reference/api-methods/add-api-key/#method-param-acl 29 | const acl = ["search"]; 30 | 31 | // Set the rate limited parameters for API key 32 | // https://www.algolia.com/doc/api-reference/api-methods/add-api-key/#method-param-maxqueriesperipperhour 33 | 34 | const params = { 35 | description: "Restricted search-only API key for algolia.com", 36 | // Rate-limit to 100 requests per hour per IP address 37 | maxQueriesPerIPPerHour: 100, 38 | }; 39 | 40 | // Create a new restricted search-only API key 41 | 42 | console.log("Creating key..."); 43 | client 44 | .addApiKey(acl, params) 45 | .wait() 46 | .then((response) => { 47 | const NEW_API_KEY = response["key"]; 48 | console.log(`Key generated successfully: ${NEW_API_KEY}`); 49 | console.log(`---------`); 50 | console.log("Testing the key..."); 51 | 52 | // Start the API client 53 | const client = algoliasearch(ALGOLIA_APP_ID, NEW_API_KEY); 54 | 55 | // # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 56 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 57 | 58 | // # Implement an empty search query 59 | index.search("").then((response) => { 60 | // # Checking connection of new API key to index 61 | !Object.keys(response).length ? console.log(`Error connecting new key to index`) : console.log(`New key connected to index successfully`); 62 | }).catch(error => console.log(error)); 63 | }); 64 | -------------------------------------------------------------------------------- /javascript/indexing.js: -------------------------------------------------------------------------------- 1 | const algoliasearch = require("algoliasearch"); 2 | const dotenv = require("dotenv"); 3 | 4 | dotenv.config(); 5 | 6 | (async () => { 7 | try { 8 | // Algolia client credentials 9 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 10 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 11 | const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME; 12 | 13 | // Initialize the client 14 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 15 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 16 | 17 | // Initialize an index 18 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 19 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 20 | 21 | const contacts = [ 22 | { 23 | name: "Foo", 24 | objectID: "1", 25 | }, 26 | { 27 | name: "Bar", 28 | objectID: "2", 29 | }, 30 | ]; 31 | 32 | // We don't have any objects (yet) in our index 33 | let res = await index.search(""); 34 | console.log("Current objects: ", res.hits); 35 | 36 | // Save objects: Add multiple objects to an index 37 | // https://www.algolia.com/doc/api-reference/api-methods/add-objects/?client=javascript 38 | console.log("Save objects - Adding multiple objects: ", contacts); 39 | await index.saveObjects(contacts).wait(); 40 | 41 | res = await index.search(""); 42 | console.log("Current objects: ", res.hits); 43 | 44 | // Save objects: replace an existing object with an updated set of attributes 45 | // https://www.algolia.com/doc/api-reference/api-methods/save-objects/?client=javascript 46 | console.log( 47 | "Save objects - Replacing objects' attributes on ", 48 | contacts[0] 49 | ); 50 | let newContact = { name: "FooBar", objectID: "1" }; 51 | await index.saveObject(newContact).wait(); 52 | 53 | res = await index.search(""); 54 | console.log("Current objects: ", res.hits); 55 | 56 | // Partially update objects: update one or more attribute of an existing object 57 | console.log("Save objects - Updating objects attributes on ", contacts[0]); 58 | newContact = { email: "foo@bar.com", objectID: "1" }; 59 | await index.partialUpdateObject(newContact).wait(); 60 | 61 | res = await index.search(""); 62 | console.log("Current objects: ", res.hits); 63 | 64 | // Delete objects: remove objects from an index using their objectID 65 | // https://www.algolia.com/doc/api-reference/api-methods/delete-objects/?client=javascript 66 | objectIDToDelete = contacts[0].objectID; 67 | console.log( 68 | `Delete objects - Deleting object with objectID ${objectIDToDelete}` 69 | ); 70 | await index.deleteObject(objectIDToDelete).wait(); 71 | 72 | res = await index.search(""); 73 | console.log("Current objects: ", res.hits); 74 | 75 | // Replace all objects: clears all objects from your index and replaces them with a 76 | // new set of objects. 77 | // https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/?client=javascript 78 | const newContacts = [ 79 | { 80 | name: "NewFoo", 81 | objectID: "3", 82 | }, 83 | { 84 | name: "NewBar", 85 | objectID: "4", 86 | }, 87 | ]; 88 | 89 | console.log( 90 | "Replace all objects - clears all objects and replaces them with ", 91 | newContacts 92 | ); 93 | await index.replaceAllObjects(newContacts).wait(); 94 | 95 | res = await index.search(""); 96 | console.log("Current objects: ", res.hits); 97 | 98 | // Delete by: remove all objects matching a filter (including geo filters) 99 | // https://www.algolia.com/doc/api-reference/api-methods/delete-by/?client=javascript 100 | console.log("Delete by - Remove all objects matching 'name:NewBar'"); 101 | 102 | // First, define an attribute to filter 103 | // https://www.algolia.com/doc/api-client/methods/settings/?client=javascript 104 | await index 105 | .setSettings({ 106 | attributesForFaceting: ["name"], 107 | }) 108 | .wait(); 109 | 110 | // https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ 111 | await index 112 | .deleteBy({ 113 | facetFilters: ["name:newBar"], 114 | }) 115 | .wait(); 116 | 117 | res = await index.search(""); 118 | console.log("Current objects: ", res.hits); 119 | 120 | // Get objects: get one or more objects by their objectIDs 121 | // https://www.algolia.com/doc/api-reference/api-methods/get-objects/?client=javascript 122 | const objectID = newContacts[0].objectID; 123 | console.log(`Get Objects - Getting object with objectID "${objectID}"`); 124 | 125 | res = await index.getObject(objectID); 126 | console.log("Results: ", res); 127 | 128 | // Custom batch: perform several indexing operations in one API call 129 | // https://www.algolia.com/doc/api-reference/api-methods/batch/?client=javascript 130 | const operations = [ 131 | { 132 | action: "addObject", 133 | indexName: ALGOLIA_INDEX_NAME, 134 | body: { 135 | name: "BatchedBar", 136 | }, 137 | }, 138 | { 139 | action: "updateObject", 140 | indexName: ALGOLIA_INDEX_NAME, 141 | body: { 142 | objectID: objectID, 143 | name: "NewBatchedBar", 144 | }, 145 | }, 146 | ]; 147 | 148 | console.log(`Custom batch - batching ${operations.length} operations`); 149 | await client.multipleBatch(operations).wait(); 150 | 151 | res = await index.search(""); 152 | console.log("Current objects: ", res.hits); 153 | 154 | // Clear objects: clear the records of an index without affecting its settings 155 | // https://www.algolia.com/doc/api-reference/api-methods/clear-objects/?client=javascript 156 | console.log( 157 | "Clear objects - clear the records of an index without affecting its settings" 158 | ); 159 | await index.clearObjects().wait(); 160 | 161 | res = await index.search(""); 162 | console.log("Current objects: ", res.hits); 163 | } catch (error) { 164 | console.error(error); 165 | } 166 | })(); 167 | -------------------------------------------------------------------------------- /javascript/list_indices_and_record_size.js: -------------------------------------------------------------------------------- 1 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript 2 | const algoliasearch = require("algoliasearch"); 3 | const dotenv = require("dotenv"); 4 | // Requiring fs module in which writeFile function is defined. 5 | const fs = require("fs"); 6 | 7 | dotenv.config(); 8 | 9 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 10 | // and choose a name for your index. Add these environment variables to a `.env` file: 11 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 12 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 13 | 14 | // Start the API client 15 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 16 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 17 | 18 | // List all indices with listIndices method 19 | // https://www.algolia.com/doc/api-reference/api-methods/list-indices/?client=javascript 20 | client.listIndices().then(({ items }) => { 21 | // Loop into each element and extract only index name and record size 22 | let filteredItems = []; 23 | items.forEach(element => filteredItems.push({ 24 | name: element.name, 25 | entries: element.entries, 26 | })); 27 | // Export JSON file containing only name of indices and record size into same directory 28 | fs.writeFile( 29 | `listIndices.json`, 30 | JSON.stringify(filteredItems), 31 | (err) => { 32 | // In case of a error throw err. 33 | if (err) throw err; 34 | } 35 | ); 36 | }) 37 | .then((response) => { 38 | // Success message 39 | console.log( 40 | `Indices name and record size saved as listIndices.json in the current directory` 41 | ); 42 | }) 43 | .catch((error) => console.log(error)); -------------------------------------------------------------------------------- /javascript/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "quickstarts", 3 | "version": "0.0.1", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "quickstarts", 9 | "version": "0.0.1", 10 | "license": "MIT", 11 | "devDependencies": { 12 | "algoliasearch": "^4.10.5", 13 | "dotenv": "^10.0.0" 14 | } 15 | }, 16 | "node_modules/@algolia/cache-browser-local-storage": { 17 | "version": "4.11.0", 18 | "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.11.0.tgz", 19 | "integrity": "sha512-4sr9vHIG1fVA9dONagdzhsI/6M5mjs/qOe2xUP0yBmwsTsuwiZq3+Xu6D3dsxsuFetcJgC6ydQoCW8b7fDJHYQ==", 20 | "dev": true, 21 | "dependencies": { 22 | "@algolia/cache-common": "4.11.0" 23 | } 24 | }, 25 | "node_modules/@algolia/cache-common": { 26 | "version": "4.11.0", 27 | "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.11.0.tgz", 28 | "integrity": "sha512-lODcJRuPXqf+6mp0h6bOxPMlbNoyn3VfjBVcQh70EDP0/xExZbkpecgHyyZK4kWg+evu+mmgvTK3GVHnet/xKw==", 29 | "dev": true 30 | }, 31 | "node_modules/@algolia/cache-in-memory": { 32 | "version": "4.11.0", 33 | "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.11.0.tgz", 34 | "integrity": "sha512-aBz+stMSTBOBaBEQ43zJXz2DnwS7fL6dR0e2myehAgtfAWlWwLDHruc/98VOy1ZAcBk1blE2LCU02bT5HekGxQ==", 35 | "dev": true, 36 | "dependencies": { 37 | "@algolia/cache-common": "4.11.0" 38 | } 39 | }, 40 | "node_modules/@algolia/client-account": { 41 | "version": "4.11.0", 42 | "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.11.0.tgz", 43 | "integrity": "sha512-jwmFBoUSzoMwMqgD3PmzFJV/d19p1RJXB6C1ADz4ju4mU7rkaQLtqyZroQpheLoU5s5Tilmn/T8/0U2XLoJCRQ==", 44 | "dev": true, 45 | "dependencies": { 46 | "@algolia/client-common": "4.11.0", 47 | "@algolia/client-search": "4.11.0", 48 | "@algolia/transporter": "4.11.0" 49 | } 50 | }, 51 | "node_modules/@algolia/client-analytics": { 52 | "version": "4.11.0", 53 | "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.11.0.tgz", 54 | "integrity": "sha512-v5U9585aeEdYml7JqggHAj3E5CQ+jPwGVztPVhakBk8H/cmLyPS2g8wvmIbaEZCHmWn4TqFj3EBHVYxAl36fSA==", 55 | "dev": true, 56 | "dependencies": { 57 | "@algolia/client-common": "4.11.0", 58 | "@algolia/client-search": "4.11.0", 59 | "@algolia/requester-common": "4.11.0", 60 | "@algolia/transporter": "4.11.0" 61 | } 62 | }, 63 | "node_modules/@algolia/client-common": { 64 | "version": "4.11.0", 65 | "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.11.0.tgz", 66 | "integrity": "sha512-Qy+F+TZq12kc7tgfC+FM3RvYH/Ati7sUiUv/LkvlxFwNwNPwWGoZO81AzVSareXT/ksDDrabD4mHbdTbBPTRmQ==", 67 | "dev": true, 68 | "dependencies": { 69 | "@algolia/requester-common": "4.11.0", 70 | "@algolia/transporter": "4.11.0" 71 | } 72 | }, 73 | "node_modules/@algolia/client-personalization": { 74 | "version": "4.11.0", 75 | "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.11.0.tgz", 76 | "integrity": "sha512-mI+X5IKiijHAzf9fy8VSl/GTT67dzFDnJ0QAM8D9cMPevnfX4U72HRln3Mjd0xEaYUOGve8TK/fMg7d3Z5yG6g==", 77 | "dev": true, 78 | "dependencies": { 79 | "@algolia/client-common": "4.11.0", 80 | "@algolia/requester-common": "4.11.0", 81 | "@algolia/transporter": "4.11.0" 82 | } 83 | }, 84 | "node_modules/@algolia/client-search": { 85 | "version": "4.11.0", 86 | "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.11.0.tgz", 87 | "integrity": "sha512-iovPLc5YgiXBdw2qMhU65sINgo9umWbHFzInxoNErWnYoTQWfXsW6P54/NlKx5uscoLVjSf+5RUWwFu5BX+lpw==", 88 | "dev": true, 89 | "dependencies": { 90 | "@algolia/client-common": "4.11.0", 91 | "@algolia/requester-common": "4.11.0", 92 | "@algolia/transporter": "4.11.0" 93 | } 94 | }, 95 | "node_modules/@algolia/logger-common": { 96 | "version": "4.11.0", 97 | "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.11.0.tgz", 98 | "integrity": "sha512-pRMJFeOY8hoWKIxWuGHIrqnEKN/kqKh7UilDffG/+PeEGxBuku+Wq5CfdTFG0C9ewUvn8mAJn5BhYA5k8y0Jqg==", 99 | "dev": true 100 | }, 101 | "node_modules/@algolia/logger-console": { 102 | "version": "4.11.0", 103 | "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.11.0.tgz", 104 | "integrity": "sha512-wXztMk0a3VbNmYP8Kpc+F7ekuvaqZmozM2eTLok0XIshpAeZ/NJDHDffXK2Pw+NF0wmHqurptLYwKoikjBYvhQ==", 105 | "dev": true, 106 | "dependencies": { 107 | "@algolia/logger-common": "4.11.0" 108 | } 109 | }, 110 | "node_modules/@algolia/requester-browser-xhr": { 111 | "version": "4.11.0", 112 | "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.11.0.tgz", 113 | "integrity": "sha512-Fp3SfDihAAFR8bllg8P5ouWi3+qpEVN5e7hrtVIYldKBOuI/qFv80Zv/3/AMKNJQRYglS4zWyPuqrXm58nz6KA==", 114 | "dev": true, 115 | "dependencies": { 116 | "@algolia/requester-common": "4.11.0" 117 | } 118 | }, 119 | "node_modules/@algolia/requester-common": { 120 | "version": "4.11.0", 121 | "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.11.0.tgz", 122 | "integrity": "sha512-+cZGe/9fuYgGuxjaBC+xTGBkK7OIYdfapxhfvEf03dviLMPmhmVYFJtJlzAjQ2YmGDJpHrGgAYj3i/fbs8yhiA==", 123 | "dev": true 124 | }, 125 | "node_modules/@algolia/requester-node-http": { 126 | "version": "4.11.0", 127 | "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.11.0.tgz", 128 | "integrity": "sha512-qJIk9SHRFkKDi6dMT9hba8X1J1z92T5AZIgl+tsApjTGIRQXJLTIm+0q4yOefokfu4CoxYwRZ9QAq+ouGwfeOg==", 129 | "dev": true, 130 | "dependencies": { 131 | "@algolia/requester-common": "4.11.0" 132 | } 133 | }, 134 | "node_modules/@algolia/transporter": { 135 | "version": "4.11.0", 136 | "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.11.0.tgz", 137 | "integrity": "sha512-k4dyxiaEfYpw4UqybK9q7lrFzehygo6KV3OCYJMMdX0IMWV0m4DXdU27c1zYRYtthaFYaBzGF4Kjcl8p8vxCKw==", 138 | "dev": true, 139 | "dependencies": { 140 | "@algolia/cache-common": "4.11.0", 141 | "@algolia/logger-common": "4.11.0", 142 | "@algolia/requester-common": "4.11.0" 143 | } 144 | }, 145 | "node_modules/algoliasearch": { 146 | "version": "4.11.0", 147 | "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.11.0.tgz", 148 | "integrity": "sha512-IXRj8kAP2WrMmj+eoPqPc6P7Ncq1yZkFiyDrjTBObV1ADNL8Z/KdZ+dWC5MmYcBLAbcB/mMCpak5N/D1UIZvsA==", 149 | "dev": true, 150 | "dependencies": { 151 | "@algolia/cache-browser-local-storage": "4.11.0", 152 | "@algolia/cache-common": "4.11.0", 153 | "@algolia/cache-in-memory": "4.11.0", 154 | "@algolia/client-account": "4.11.0", 155 | "@algolia/client-analytics": "4.11.0", 156 | "@algolia/client-common": "4.11.0", 157 | "@algolia/client-personalization": "4.11.0", 158 | "@algolia/client-search": "4.11.0", 159 | "@algolia/logger-common": "4.11.0", 160 | "@algolia/logger-console": "4.11.0", 161 | "@algolia/requester-browser-xhr": "4.11.0", 162 | "@algolia/requester-common": "4.11.0", 163 | "@algolia/requester-node-http": "4.11.0", 164 | "@algolia/transporter": "4.11.0" 165 | } 166 | }, 167 | "node_modules/dotenv": { 168 | "version": "10.0.0", 169 | "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz", 170 | "integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==", 171 | "dev": true, 172 | "engines": { 173 | "node": ">=10" 174 | } 175 | } 176 | }, 177 | "dependencies": { 178 | "@algolia/cache-browser-local-storage": { 179 | "version": "4.11.0", 180 | "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.11.0.tgz", 181 | "integrity": "sha512-4sr9vHIG1fVA9dONagdzhsI/6M5mjs/qOe2xUP0yBmwsTsuwiZq3+Xu6D3dsxsuFetcJgC6ydQoCW8b7fDJHYQ==", 182 | "dev": true, 183 | "requires": { 184 | "@algolia/cache-common": "4.11.0" 185 | } 186 | }, 187 | "@algolia/cache-common": { 188 | "version": "4.11.0", 189 | "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.11.0.tgz", 190 | "integrity": "sha512-lODcJRuPXqf+6mp0h6bOxPMlbNoyn3VfjBVcQh70EDP0/xExZbkpecgHyyZK4kWg+evu+mmgvTK3GVHnet/xKw==", 191 | "dev": true 192 | }, 193 | "@algolia/cache-in-memory": { 194 | "version": "4.11.0", 195 | "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.11.0.tgz", 196 | "integrity": "sha512-aBz+stMSTBOBaBEQ43zJXz2DnwS7fL6dR0e2myehAgtfAWlWwLDHruc/98VOy1ZAcBk1blE2LCU02bT5HekGxQ==", 197 | "dev": true, 198 | "requires": { 199 | "@algolia/cache-common": "4.11.0" 200 | } 201 | }, 202 | "@algolia/client-account": { 203 | "version": "4.11.0", 204 | "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.11.0.tgz", 205 | "integrity": "sha512-jwmFBoUSzoMwMqgD3PmzFJV/d19p1RJXB6C1ADz4ju4mU7rkaQLtqyZroQpheLoU5s5Tilmn/T8/0U2XLoJCRQ==", 206 | "dev": true, 207 | "requires": { 208 | "@algolia/client-common": "4.11.0", 209 | "@algolia/client-search": "4.11.0", 210 | "@algolia/transporter": "4.11.0" 211 | } 212 | }, 213 | "@algolia/client-analytics": { 214 | "version": "4.11.0", 215 | "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.11.0.tgz", 216 | "integrity": "sha512-v5U9585aeEdYml7JqggHAj3E5CQ+jPwGVztPVhakBk8H/cmLyPS2g8wvmIbaEZCHmWn4TqFj3EBHVYxAl36fSA==", 217 | "dev": true, 218 | "requires": { 219 | "@algolia/client-common": "4.11.0", 220 | "@algolia/client-search": "4.11.0", 221 | "@algolia/requester-common": "4.11.0", 222 | "@algolia/transporter": "4.11.0" 223 | } 224 | }, 225 | "@algolia/client-common": { 226 | "version": "4.11.0", 227 | "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.11.0.tgz", 228 | "integrity": "sha512-Qy+F+TZq12kc7tgfC+FM3RvYH/Ati7sUiUv/LkvlxFwNwNPwWGoZO81AzVSareXT/ksDDrabD4mHbdTbBPTRmQ==", 229 | "dev": true, 230 | "requires": { 231 | "@algolia/requester-common": "4.11.0", 232 | "@algolia/transporter": "4.11.0" 233 | } 234 | }, 235 | "@algolia/client-personalization": { 236 | "version": "4.11.0", 237 | "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.11.0.tgz", 238 | "integrity": "sha512-mI+X5IKiijHAzf9fy8VSl/GTT67dzFDnJ0QAM8D9cMPevnfX4U72HRln3Mjd0xEaYUOGve8TK/fMg7d3Z5yG6g==", 239 | "dev": true, 240 | "requires": { 241 | "@algolia/client-common": "4.11.0", 242 | "@algolia/requester-common": "4.11.0", 243 | "@algolia/transporter": "4.11.0" 244 | } 245 | }, 246 | "@algolia/client-search": { 247 | "version": "4.11.0", 248 | "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.11.0.tgz", 249 | "integrity": "sha512-iovPLc5YgiXBdw2qMhU65sINgo9umWbHFzInxoNErWnYoTQWfXsW6P54/NlKx5uscoLVjSf+5RUWwFu5BX+lpw==", 250 | "dev": true, 251 | "requires": { 252 | "@algolia/client-common": "4.11.0", 253 | "@algolia/requester-common": "4.11.0", 254 | "@algolia/transporter": "4.11.0" 255 | } 256 | }, 257 | "@algolia/logger-common": { 258 | "version": "4.11.0", 259 | "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.11.0.tgz", 260 | "integrity": "sha512-pRMJFeOY8hoWKIxWuGHIrqnEKN/kqKh7UilDffG/+PeEGxBuku+Wq5CfdTFG0C9ewUvn8mAJn5BhYA5k8y0Jqg==", 261 | "dev": true 262 | }, 263 | "@algolia/logger-console": { 264 | "version": "4.11.0", 265 | "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.11.0.tgz", 266 | "integrity": "sha512-wXztMk0a3VbNmYP8Kpc+F7ekuvaqZmozM2eTLok0XIshpAeZ/NJDHDffXK2Pw+NF0wmHqurptLYwKoikjBYvhQ==", 267 | "dev": true, 268 | "requires": { 269 | "@algolia/logger-common": "4.11.0" 270 | } 271 | }, 272 | "@algolia/requester-browser-xhr": { 273 | "version": "4.11.0", 274 | "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.11.0.tgz", 275 | "integrity": "sha512-Fp3SfDihAAFR8bllg8P5ouWi3+qpEVN5e7hrtVIYldKBOuI/qFv80Zv/3/AMKNJQRYglS4zWyPuqrXm58nz6KA==", 276 | "dev": true, 277 | "requires": { 278 | "@algolia/requester-common": "4.11.0" 279 | } 280 | }, 281 | "@algolia/requester-common": { 282 | "version": "4.11.0", 283 | "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.11.0.tgz", 284 | "integrity": "sha512-+cZGe/9fuYgGuxjaBC+xTGBkK7OIYdfapxhfvEf03dviLMPmhmVYFJtJlzAjQ2YmGDJpHrGgAYj3i/fbs8yhiA==", 285 | "dev": true 286 | }, 287 | "@algolia/requester-node-http": { 288 | "version": "4.11.0", 289 | "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.11.0.tgz", 290 | "integrity": "sha512-qJIk9SHRFkKDi6dMT9hba8X1J1z92T5AZIgl+tsApjTGIRQXJLTIm+0q4yOefokfu4CoxYwRZ9QAq+ouGwfeOg==", 291 | "dev": true, 292 | "requires": { 293 | "@algolia/requester-common": "4.11.0" 294 | } 295 | }, 296 | "@algolia/transporter": { 297 | "version": "4.11.0", 298 | "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.11.0.tgz", 299 | "integrity": "sha512-k4dyxiaEfYpw4UqybK9q7lrFzehygo6KV3OCYJMMdX0IMWV0m4DXdU27c1zYRYtthaFYaBzGF4Kjcl8p8vxCKw==", 300 | "dev": true, 301 | "requires": { 302 | "@algolia/cache-common": "4.11.0", 303 | "@algolia/logger-common": "4.11.0", 304 | "@algolia/requester-common": "4.11.0" 305 | } 306 | }, 307 | "algoliasearch": { 308 | "version": "4.11.0", 309 | "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.11.0.tgz", 310 | "integrity": "sha512-IXRj8kAP2WrMmj+eoPqPc6P7Ncq1yZkFiyDrjTBObV1ADNL8Z/KdZ+dWC5MmYcBLAbcB/mMCpak5N/D1UIZvsA==", 311 | "dev": true, 312 | "requires": { 313 | "@algolia/cache-browser-local-storage": "4.11.0", 314 | "@algolia/cache-common": "4.11.0", 315 | "@algolia/cache-in-memory": "4.11.0", 316 | "@algolia/client-account": "4.11.0", 317 | "@algolia/client-analytics": "4.11.0", 318 | "@algolia/client-common": "4.11.0", 319 | "@algolia/client-personalization": "4.11.0", 320 | "@algolia/client-search": "4.11.0", 321 | "@algolia/logger-common": "4.11.0", 322 | "@algolia/logger-console": "4.11.0", 323 | "@algolia/requester-browser-xhr": "4.11.0", 324 | "@algolia/requester-common": "4.11.0", 325 | "@algolia/requester-node-http": "4.11.0", 326 | "@algolia/transporter": "4.11.0" 327 | } 328 | }, 329 | "dotenv": { 330 | "version": "10.0.0", 331 | "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz", 332 | "integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==", 333 | "dev": true 334 | } 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /javascript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "quickstarts", 3 | "version": "0.0.1", 4 | "author": "Algolia Samples", 5 | "license": "MIT", 6 | "devDependencies": { 7 | "algoliasearch": "^4.10.5", 8 | "dotenv": "^10.0.0" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /javascript/rest_API_return_top_1000_hits.js: -------------------------------------------------------------------------------- 1 | /* 2 | Analytics API Query 3 | This script makes a GET request to the /searches endpoint on the Analytics REST API - https://www.algolia.com/doc/rest-api/analytics/. 4 | To get the top 1000 searches over the last 7 days. 5 | There is no API client for Analytics, so this script uses the JavaScript Requests library to make the call. 6 | */ 7 | try { 8 | const dotenv = require("dotenv"); 9 | dotenv.config(); 10 | 11 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 12 | // use the name of the index you want to target. Add these environment variables to the `.env` file: 13 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 14 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 15 | const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME; 16 | const URL_DOMAIN = process.env.URL_DOMAIN; 17 | 18 | const fs = require("fs"); 19 | 20 | /* 21 | # The Analytics API can be reached from multiple domains, each specific to a region. 22 | # You should use the domain that matches the region where your analytics data is stored and processed. 23 | # View your analytics region: https://www.algolia.com/infra/analytics 24 | # The following domains are available: 25 | # United States: https://analytics.us.algolia.com 26 | # Europe (Germany): https://analytics.de.algolia.com 27 | Add this environment variable to the '.env' file 28 | */ 29 | 30 | let url = `https://analytics.${URL_DOMAIN}.algolia.com`; 31 | 32 | // // Create fetch request to Rest API for top searches limited to 1000 33 | // https://www.algolia.com/doc/rest-api/analytics/#get-top-searches 34 | (async () => { 35 | const response = await fetch( 36 | `${url}/2/searches?index=${ALGOLIA_INDEX_NAME}&limit=1000`, 37 | { 38 | method: "GET", 39 | headers: { 40 | "X-Algolia-API-Key": `${ALGOLIA_API_KEY}`, 41 | "X-Algolia-Application-Id": `${ALGOLIA_APP_ID}`, 42 | }, 43 | } 44 | ); 45 | if (!response.ok) { 46 | throw new Error(`HTTP error! status: ${response.status}`); 47 | } 48 | const data = await response.json(); 49 | console.log("creating JSON file..."); 50 | // Create JSON file and export to current directory 51 | fs.writeFile( 52 | `${ALGOLIA_INDEX_NAME}_top_1000_searches.json`, 53 | JSON.stringify(data), 54 | (err) => { 55 | if (err) throw err; 56 | } 57 | ); 58 | console.log(`JSON file "${ALGOLIA_INDEX_NAME}_top_1000_searches" created!`); 59 | })(); 60 | } catch (er) { 61 | console.log(er) 62 | } 63 | -------------------------------------------------------------------------------- /javascript/restore_index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Restore Index 3 | 4 | This script will restore an index, including any settings, rules and synonyms. 5 | 6 | It is best used in conjuction with backup_index.js to backup and restore an index to an application. 7 | 8 | When run, the user will be prompted to enter an index name. The script will look for files prefixed 9 | with this index name to use for the restore. E.g. if the index name is 'my-index', the script will 10 | look for 'my-index_index.json', 'my-index_rules.json', 'my-index_settings.json' and 11 | 'my-index_synonyms.json' files in the same directory. 12 | 13 | This script will overwrite any existing indexes with the same name. 14 | */ 15 | 16 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript 17 | const algoliasearch = require("algoliasearch"); 18 | const dotenv = require("dotenv"); 19 | dotenv.config(); 20 | 21 | // Requiring built in modules for fs (file system) and readline (console interface) 22 | const fs = require("fs"); 23 | const readline = require("readline"); 24 | 25 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 26 | // Add these 2 environment variables to a `.env` file: 27 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 28 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 29 | 30 | // Start the API client 31 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 32 | 33 | // Initiate interface for console 34 | const rl = readline.createInterface({ 35 | input: process.stdin, 36 | output: process.stdout, 37 | }); 38 | 39 | // Function to ask user for index name 40 | let ALGOLIA_INDEX_NAME; 41 | 42 | const askForIndexName = async () => { 43 | while (true) { 44 | try { 45 | const name = await new Promise((resolve, reject) => { 46 | rl.question( 47 | "Please enter an index name to restore the backup to: ", 48 | (input) => { 49 | if (!input) { 50 | reject(new Error("Index name cannot be empty")); 51 | } else { 52 | resolve(input); 53 | } 54 | } 55 | ); 56 | }); 57 | ALGOLIA_INDEX_NAME = name; 58 | const answer = await new Promise((resolve, reject) => { 59 | rl.question( 60 | `You entered ${ALGOLIA_INDEX_NAME}, is this correct? (yes/no) `, 61 | (input) => { 62 | if (input.toLowerCase() !== "yes" && input.toLowerCase() !== "y") { 63 | reject(new Error("Invalid answer")); 64 | } else { 65 | resolve(input); 66 | } 67 | } 68 | ); 69 | }); 70 | console.log(`Index name is: ${ALGOLIA_INDEX_NAME}`); 71 | return name; 72 | } catch (err) { 73 | console.error(err.message); 74 | } 75 | } 76 | }; 77 | 78 | (async () => { 79 | // Assign correct index 80 | ALGOLIA_INDEX_NAME = await askForIndexName(); 81 | 82 | // Connect to the index 83 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 84 | 85 | // Check if input has been received before proceeding with the rest of the script 86 | 87 | const is_index_file = `./${ALGOLIA_INDEX_NAME}_records.json`; 88 | const is_rules_file = `./${ALGOLIA_INDEX_NAME}_rules.json`; 89 | const is_settings_file = `./${ALGOLIA_INDEX_NAME}_settings.json`; 90 | const is_synonyms_file = `./${ALGOLIA_INDEX_NAME}_synonyms.json`; 91 | 92 | let index_data = []; 93 | let rules_data; 94 | let settings_data; 95 | let synonyms_data; 96 | if (!fs.existsSync(is_index_file)) { 97 | console.log("No index file available. Terminating script."); 98 | rl.close(); 99 | return; 100 | } else { 101 | index_data = JSON.parse(fs.readFileSync(is_index_file, "utf8")); 102 | } 103 | 104 | if (is_rules_file) { 105 | rules_data = JSON.parse(fs.readFileSync(is_rules_file, "utf8")); 106 | } 107 | 108 | if (is_settings_file) { 109 | settings_data = JSON.parse(fs.readFileSync(is_settings_file, "utf8")); 110 | } 111 | 112 | if (is_synonyms_file) { 113 | synonyms_data = JSON.parse(fs.readFileSync(is_synonyms_file, "utf8")); 114 | } 115 | 116 | // Check the status of the current index. 117 | let existing_records = []; 118 | try { 119 | await index.browseObjects({ 120 | attributesToRetrieve: ["objectId"], 121 | batch: (batch) => { 122 | existing_records = existing_records.concat(batch); 123 | }, 124 | }); 125 | } catch (error) { 126 | console.log(`Error querying existing index. ${error}. Exiting script`); 127 | return; 128 | } 129 | 130 | // Confirm with the user that user will overwrite an existing index, then proceed to overwrite 131 | 132 | const askQuestion = () => { 133 | console.log(` 134 | WARNING: Continuing will overwrite ${existing_records.length} records in existing index "${ALGOLIA_INDEX_NAME}" with ${index_data.length} records from local index. \ 135 | Do you want to continue (Y/N): `); 136 | rl.question("", (confirmation) => { 137 | confirmation = confirmation.trim().toLowerCase(); 138 | switch (confirmation) { 139 | default: 140 | console.log(`please enter 'yes', 'y', 'no', or 'n'`); 141 | askQuestion(); 142 | break; 143 | case "no": 144 | case "n": 145 | console.log("exiting script"); 146 | rl.close(); 147 | break; 148 | case "yes": 149 | case "y": 150 | try { 151 | // Restore the index and associated data to the application. 152 | console.log("Restoring index..."); 153 | index.replaceAllObjects(index_data, { 154 | safe: true, 155 | }); 156 | console.log("Index restored."); 157 | if (is_rules_file) { 158 | console.log("Restoring rules..."); 159 | index.replaceAllRules(rules_data); 160 | console.log("Rules restored..."); 161 | } 162 | 163 | if (is_settings_file) { 164 | console.log("Restoring settings..."); 165 | index.setSettings(settings_data); 166 | console.log("Settings restored..."); 167 | } 168 | 169 | if (is_synonyms_file) { 170 | console.log("Restoring synonyms..."); 171 | index.replaceAllSynonyms(synonyms_data); 172 | console.log("Synonyms restored..."); 173 | } 174 | } catch (error) { 175 | console.log(`error restoring data. ${error}`); 176 | } 177 | rl.close(); 178 | break; 179 | } 180 | }); 181 | }; 182 | 183 | askQuestion(); 184 | })(); 185 | -------------------------------------------------------------------------------- /javascript/simple.js: -------------------------------------------------------------------------------- 1 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript 2 | const algoliasearch = require("algoliasearch"); 3 | const dotenv = require("dotenv"); 4 | 5 | dotenv.config(); 6 | 7 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 8 | // and choose a name for your index. Add these environment variables to a `.env` file: 9 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 10 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 11 | const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME; 12 | 13 | // Start the API client 14 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 15 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 16 | 17 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 18 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 19 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 20 | 21 | // Add new objects to the index 22 | // https://www.algolia.com/doc/api-reference/api-methods/add-objects/ 23 | const newObject = { objectID: 1, name: "Foo" }; 24 | 25 | index 26 | .saveObjects([newObject]) 27 | // Wait for the indexing task to complete 28 | // https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 29 | .wait() 30 | .then((response) => { 31 | console.log(response); 32 | // Search the index for "Fo" 33 | // https://www.algolia.com/doc/api-reference/api-methods/search/ 34 | index.search("Fo").then((objects) => console.log(objects)).catch(); 35 | }) ; 36 | 37 | 38 | -------------------------------------------------------------------------------- /javascript/sort_index_by_record_size.js: -------------------------------------------------------------------------------- 1 | /* 2 | Sort Index By Record Size 3 | Sometimes we want to easily find the largest record in an index (in file size) so we can investigate situations where some small number of records are over the fileSizeLimit. This script is designed to fetch the entire index and then sort it by the total string size, and then export it to a file for analysis. 4 | */ 5 | 6 | // Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript 7 | const algoliasearch = require("algoliasearch"); 8 | const dotenv = require("dotenv"); 9 | 10 | dotenv.config(); 11 | 12 | // Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 13 | // and choose a name for your index. Add these environment variables to a `.env` file: 14 | const ALGOLIA_APP_ID = process.env.ALGOLIA_APP_ID; 15 | const ALGOLIA_API_KEY = process.env.ALGOLIA_API_KEY; 16 | const ALGOLIA_INDEX_NAME = process.env.ALGOLIA_INDEX_NAME; 17 | 18 | // Start the API client 19 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 20 | const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 21 | 22 | // Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 23 | // https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 24 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 25 | 26 | // Requiring fs module in which writeFile function is defined. 27 | const fs = require("fs"); 28 | 29 | let records = []; 30 | 31 | (async () => { 32 | // retrieve all records from index 33 | console.log(`Retrieving records...`); 34 | try { 35 | await index.browseObjects({ 36 | batch: (batch) => { 37 | 38 | // This method gets an approximation of the size of the record (total string length) we can use for sorting purposes 39 | for (let i = 0; i < batch.length; i++) { 40 | batch[i].string_length = JSON.stringify(batch[i]).length; 41 | } 42 | records = records.concat(batch); 43 | } 44 | }); 45 | 46 | console.log(`${records.length} records retrieved`); 47 | 48 | console.log(`Sorting Records By Size...`); 49 | 50 | // Sort the result so the largest string length is at the beggining 51 | records.sort((a, b) => b.string_length - a.string_length); 52 | 53 | 54 | } catch (error) { 55 | console.log(`Error retrieving data ${error.message}`); 56 | } 57 | 58 | // write json files to current directory 59 | function createJson(data, name) { 60 | if (data) { 61 | fs.writeFile( 62 | `${ALGOLIA_INDEX_NAME}_${name}.json`, 63 | JSON.stringify(data), 64 | (err) => { 65 | if (err) throw err; 66 | } 67 | ); 68 | } else 69 | (error) => { 70 | console.log(`Error writing files: ${error.message}`); 71 | }; 72 | } 73 | try { 74 | let name = "records"; 75 | createJson(records, name); 76 | } catch (error) { 77 | console.log(`Error exporting data ${error.message}`); 78 | } 79 | })(); 80 | -------------------------------------------------------------------------------- /javascript/yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | "@algolia/cache-browser-local-storage@4.11.0": 6 | "integrity" "sha512-4sr9vHIG1fVA9dONagdzhsI/6M5mjs/qOe2xUP0yBmwsTsuwiZq3+Xu6D3dsxsuFetcJgC6ydQoCW8b7fDJHYQ==" 7 | "resolved" "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.11.0.tgz" 8 | "version" "4.11.0" 9 | dependencies: 10 | "@algolia/cache-common" "4.11.0" 11 | 12 | "@algolia/cache-common@4.11.0": 13 | "integrity" "sha512-lODcJRuPXqf+6mp0h6bOxPMlbNoyn3VfjBVcQh70EDP0/xExZbkpecgHyyZK4kWg+evu+mmgvTK3GVHnet/xKw==" 14 | "resolved" "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.11.0.tgz" 15 | "version" "4.11.0" 16 | 17 | "@algolia/cache-in-memory@4.11.0": 18 | "integrity" "sha512-aBz+stMSTBOBaBEQ43zJXz2DnwS7fL6dR0e2myehAgtfAWlWwLDHruc/98VOy1ZAcBk1blE2LCU02bT5HekGxQ==" 19 | "resolved" "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.11.0.tgz" 20 | "version" "4.11.0" 21 | dependencies: 22 | "@algolia/cache-common" "4.11.0" 23 | 24 | "@algolia/client-account@4.11.0": 25 | "integrity" "sha512-jwmFBoUSzoMwMqgD3PmzFJV/d19p1RJXB6C1ADz4ju4mU7rkaQLtqyZroQpheLoU5s5Tilmn/T8/0U2XLoJCRQ==" 26 | "resolved" "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.11.0.tgz" 27 | "version" "4.11.0" 28 | dependencies: 29 | "@algolia/client-common" "4.11.0" 30 | "@algolia/client-search" "4.11.0" 31 | "@algolia/transporter" "4.11.0" 32 | 33 | "@algolia/client-analytics@4.11.0": 34 | "integrity" "sha512-v5U9585aeEdYml7JqggHAj3E5CQ+jPwGVztPVhakBk8H/cmLyPS2g8wvmIbaEZCHmWn4TqFj3EBHVYxAl36fSA==" 35 | "resolved" "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.11.0.tgz" 36 | "version" "4.11.0" 37 | dependencies: 38 | "@algolia/client-common" "4.11.0" 39 | "@algolia/client-search" "4.11.0" 40 | "@algolia/requester-common" "4.11.0" 41 | "@algolia/transporter" "4.11.0" 42 | 43 | "@algolia/client-common@4.11.0": 44 | "integrity" "sha512-Qy+F+TZq12kc7tgfC+FM3RvYH/Ati7sUiUv/LkvlxFwNwNPwWGoZO81AzVSareXT/ksDDrabD4mHbdTbBPTRmQ==" 45 | "resolved" "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.11.0.tgz" 46 | "version" "4.11.0" 47 | dependencies: 48 | "@algolia/requester-common" "4.11.0" 49 | "@algolia/transporter" "4.11.0" 50 | 51 | "@algolia/client-personalization@4.11.0": 52 | "integrity" "sha512-mI+X5IKiijHAzf9fy8VSl/GTT67dzFDnJ0QAM8D9cMPevnfX4U72HRln3Mjd0xEaYUOGve8TK/fMg7d3Z5yG6g==" 53 | "resolved" "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.11.0.tgz" 54 | "version" "4.11.0" 55 | dependencies: 56 | "@algolia/client-common" "4.11.0" 57 | "@algolia/requester-common" "4.11.0" 58 | "@algolia/transporter" "4.11.0" 59 | 60 | "@algolia/client-search@4.11.0": 61 | "integrity" "sha512-iovPLc5YgiXBdw2qMhU65sINgo9umWbHFzInxoNErWnYoTQWfXsW6P54/NlKx5uscoLVjSf+5RUWwFu5BX+lpw==" 62 | "resolved" "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.11.0.tgz" 63 | "version" "4.11.0" 64 | dependencies: 65 | "@algolia/client-common" "4.11.0" 66 | "@algolia/requester-common" "4.11.0" 67 | "@algolia/transporter" "4.11.0" 68 | 69 | "@algolia/logger-common@4.11.0": 70 | "integrity" "sha512-pRMJFeOY8hoWKIxWuGHIrqnEKN/kqKh7UilDffG/+PeEGxBuku+Wq5CfdTFG0C9ewUvn8mAJn5BhYA5k8y0Jqg==" 71 | "resolved" "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.11.0.tgz" 72 | "version" "4.11.0" 73 | 74 | "@algolia/logger-console@4.11.0": 75 | "integrity" "sha512-wXztMk0a3VbNmYP8Kpc+F7ekuvaqZmozM2eTLok0XIshpAeZ/NJDHDffXK2Pw+NF0wmHqurptLYwKoikjBYvhQ==" 76 | "resolved" "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.11.0.tgz" 77 | "version" "4.11.0" 78 | dependencies: 79 | "@algolia/logger-common" "4.11.0" 80 | 81 | "@algolia/requester-browser-xhr@4.11.0": 82 | "integrity" "sha512-Fp3SfDihAAFR8bllg8P5ouWi3+qpEVN5e7hrtVIYldKBOuI/qFv80Zv/3/AMKNJQRYglS4zWyPuqrXm58nz6KA==" 83 | "resolved" "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.11.0.tgz" 84 | "version" "4.11.0" 85 | dependencies: 86 | "@algolia/requester-common" "4.11.0" 87 | 88 | "@algolia/requester-common@4.11.0": 89 | "integrity" "sha512-+cZGe/9fuYgGuxjaBC+xTGBkK7OIYdfapxhfvEf03dviLMPmhmVYFJtJlzAjQ2YmGDJpHrGgAYj3i/fbs8yhiA==" 90 | "resolved" "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.11.0.tgz" 91 | "version" "4.11.0" 92 | 93 | "@algolia/requester-node-http@4.11.0": 94 | "integrity" "sha512-qJIk9SHRFkKDi6dMT9hba8X1J1z92T5AZIgl+tsApjTGIRQXJLTIm+0q4yOefokfu4CoxYwRZ9QAq+ouGwfeOg==" 95 | "resolved" "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.11.0.tgz" 96 | "version" "4.11.0" 97 | dependencies: 98 | "@algolia/requester-common" "4.11.0" 99 | 100 | "@algolia/transporter@4.11.0": 101 | "integrity" "sha512-k4dyxiaEfYpw4UqybK9q7lrFzehygo6KV3OCYJMMdX0IMWV0m4DXdU27c1zYRYtthaFYaBzGF4Kjcl8p8vxCKw==" 102 | "resolved" "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.11.0.tgz" 103 | "version" "4.11.0" 104 | dependencies: 105 | "@algolia/cache-common" "4.11.0" 106 | "@algolia/logger-common" "4.11.0" 107 | "@algolia/requester-common" "4.11.0" 108 | 109 | "algoliasearch@^4.10.5": 110 | "integrity" "sha512-IXRj8kAP2WrMmj+eoPqPc6P7Ncq1yZkFiyDrjTBObV1ADNL8Z/KdZ+dWC5MmYcBLAbcB/mMCpak5N/D1UIZvsA==" 111 | "resolved" "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.11.0.tgz" 112 | "version" "4.11.0" 113 | dependencies: 114 | "@algolia/cache-browser-local-storage" "4.11.0" 115 | "@algolia/cache-common" "4.11.0" 116 | "@algolia/cache-in-memory" "4.11.0" 117 | "@algolia/client-account" "4.11.0" 118 | "@algolia/client-analytics" "4.11.0" 119 | "@algolia/client-common" "4.11.0" 120 | "@algolia/client-personalization" "4.11.0" 121 | "@algolia/client-search" "4.11.0" 122 | "@algolia/logger-common" "4.11.0" 123 | "@algolia/logger-console" "4.11.0" 124 | "@algolia/requester-browser-xhr" "4.11.0" 125 | "@algolia/requester-common" "4.11.0" 126 | "@algolia/requester-node-http" "4.11.0" 127 | "@algolia/transporter" "4.11.0" 128 | 129 | "dotenv@^10.0.0": 130 | "integrity" "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==" 131 | "resolved" "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz" 132 | "version" "10.0.0" 133 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-clients-quickstarts", 3 | "lockfileVersion": 2, 4 | "requires": true, 5 | "packages": {} 6 | } 7 | -------------------------------------------------------------------------------- /php/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] PHP version (use -bullseye variants on local arm64/Apple Silicon): 8, 8.0, 7, 7.4, 7.3, 8-bullseye, 8.0-bullseye, 7-bullseye, 7.4-bullseye, 7.3-bullseye, 8-buster, 8.0-buster, 7-buster, 7.4-buster, 7.3-buster 2 | ARG VARIANT=7-bullseye 3 | FROM mcr.microsoft.com/vscode/devcontainers/php:${VARIANT} 4 | 5 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 6 | ARG NODE_VERSION="none" 7 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 8 | 9 | # [Optional] Uncomment this section to install additional OS packages. 10 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 11 | # && apt-get -y install --no-install-recommends 12 | 13 | # [Optional] Uncomment this line to install global node packages. 14 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /php/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "PHP", 3 | "runArgs": ["--init"], 4 | "build": { 5 | "dockerfile": "Dockerfile", 6 | }, 7 | 8 | // Set *default* container specific settings.json values on container create. 9 | "settings": { 10 | "php.validate.executablePath": "/usr/local/bin/php" 11 | }, 12 | 13 | // Add the IDs of extensions you want installed when the container is created. 14 | "extensions": [ 15 | "felixfbecker.php-debug", 16 | "bmewburn.vscode-intelephense-client", 17 | "mrmlnc.vscode-apache" 18 | ], 19 | 20 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 21 | // "forwardPorts": [8080], 22 | 23 | // Use 'postCreateCommand' to run commands after the container is created. 24 | // "postCreateCommand": "sudo chmod a+x \"$(pwd)\" && sudo rm -rf /var/www/html && sudo ln -s \"$(pwd)\" /var/www/html" 25 | 26 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 27 | "postStartCommand": "composer install" 28 | } -------------------------------------------------------------------------------- /php/.dockerignore: -------------------------------------------------------------------------------- 1 | .php_cs.cache 2 | .idea/ 3 | .php_cs.dist 4 | /vendor/ -------------------------------------------------------------------------------- /php/.env.example: -------------------------------------------------------------------------------- 1 | ALGOLIA_APP_ID= 2 | ALGOLIA_API_KEY= 3 | ALGOLIA_INDEX_NAME= -------------------------------------------------------------------------------- /php/README.md: -------------------------------------------------------------------------------- 1 | # API Clients Quickstarts: PHP 2 | 3 | This quickstart demonstrates various usages of the the [Algolia PHP API Client](https://www.algolia.com/doc/api-client/getting-started/install/python/?client=php). 4 | 5 | ## Setting up the quickstart 6 | 7 | ### Prerequisites 8 | 9 | - An Algolia account. If you don't have one already, [create an account for free](https://www.algolia.com/users/sign_up). 10 | - A PHP ^7.2 local environment, or [Docker](https://www.docker.com/get-started). 11 | 12 |
13 | Using VSCode 14 | 15 | By using VScode and having the [Visual Studio Code Remote - Containers](https://code.visualstudio.com/docs/remote/containers) extension installed, you can run any of the quickstarts by using the command [Remote-Containers: Open Folder in Container](https://code.visualstudio.com/docs/remote/containers#_quick-start-open-an-existing-folder-in-a-container) command. 16 | 17 | Each of the quickstart contains a [.devcontainer.json](./.devcontainer/devcontainer.json), along with a [Dockerfile](./.devcontainer/Dockerfile). 18 |
19 | 20 | 1. Create an Algolia Application and an [Algolia Index](https://www.algolia.com/doc/guides/getting-started/quick-start/tutorials/getting-started-with-the-dashboard/#indices) 21 | 2. Copy the file [.env.example](.env.example) and rename it to `.env` 22 | 3. Set the environment variables `ALGOLIA_APP_ID`, `ALGOLIA_API_KEY` and `ALGOLIA_INDEX_NAME` in the `.env` file. You can obtain those from the [Algolia Dashboard](https://www.algolia.com/api-keys/). The `ALGOLIA_API_KEY` should be the "Admin API Key" (necessary for indexing). 23 | 24 | ## How to use 25 | 26 | Once setup, you can run each of the script in this folder using the PHP command line. 27 | Example: to execute the `simple.php` script: 28 | 29 | ```bash 30 | php simple.php 31 | ``` 32 | 33 | ## Available quickstarts 34 | 35 | | File | Description | 36 | | ------------- | ------------- | 37 | | [simple.php](./simple.php) | Index a single object and run a search query | 38 | | [indexing.php](./indexing.php) | Showcase of the main indexing methods | 39 | | [change_index_settings.php](./change_index_settings.php) | Change index settings | 40 | | [rules.php](./rules.php) | Export rules and add a new rule to an index | 41 | | [backup.php](./backup.php) | Backup an index | 42 | | [restore.php](./restore.php) | Restore an index | 43 | | [rest_api_return_top_hits.php](./rest_api_return_top_hits.php) | Get top 1000 searches with Analytics REST API | 44 | | [generate_key.php](./generate_key.php) | Generate a rate-limited search only API key | 45 | -------------------------------------------------------------------------------- /php/backup.php: -------------------------------------------------------------------------------- 1 | load(); 8 | 9 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 10 | # and choose a name for your index. Add these environment variables to a `.env` file: 11 | $ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; 12 | $ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; 13 | $ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; 14 | 15 | # Start the API client 16 | # https://www.algolia.com/doc/api-client/getting-started/initialize/php/?client=php#initialize-the-search-client 17 | $client = \Algolia\AlgoliaSearch\SearchClient::create($ALGOLIA_APP_ID, $ALGOLIA_API_KEY); 18 | 19 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 20 | # https://www.algolia.com/doc/api-client/getting-started/initialize/php/?client=php#initialize-the-search-client 21 | $index = $client->initIndex($ALGOLIA_INDEX_NAME); 22 | 23 | # Get all records from an index 24 | # https://www.algolia.com/doc/api-reference/api-methods/browse/#get-all-records-from-an-index 25 | # Use an API key with `browse` ACL 26 | print("All the records:"); 27 | $records = $index->browseObjects(); 28 | var_dump($records); 29 | print("\n"); 30 | 31 | # Transform records iterator to array 32 | $all_records = iterator_to_array($records); 33 | 34 | # Encode array to json 35 | $jsonRecords = json_encode($all_records); 36 | 37 | # Write json to file 38 | if (file_put_contents("{$ALGOLIA_INDEX_NAME}_records.json", $jsonRecords)) 39 | echo "JSON file created successfully...\n"; 40 | else 41 | echo "Oops! Error creating json file...\n"; 42 | 43 | # Retrieve settings for an index 44 | # https://www.algolia.com/doc/api-reference/api-methods/get-settings/#retrieve-settings-for-an-index 45 | print("Index settings:\n"); 46 | $settings = $index->getSettings(); 47 | var_dump($settings); 48 | print("\n"); 49 | 50 | # Encode array to json 51 | $jsonSettings = json_encode($settings); 52 | 53 | # Write json to file 54 | if (file_put_contents("{$ALGOLIA_INDEX_NAME}_settings.json", $jsonSettings)) 55 | echo "JSON file created successfully...\n"; 56 | else 57 | echo "Oops! Error creating json file...\n"; 58 | 59 | # Export rules 60 | # https://www.algolia.com/doc/api-reference/api-methods/export-rules/ 61 | print("Rules:\n"); 62 | $rules = $index->browseRules(); 63 | var_dump($rules); 64 | print("\n"); 65 | 66 | # Transform rules iterator to array 67 | $all_rules = iterator_to_array($rules); 68 | 69 | # Encode array to json 70 | $jsonRules = json_encode($all_rules); 71 | 72 | # Write json to file 73 | if (file_put_contents("{$ALGOLIA_INDEX_NAME}_rules.json", $jsonRules)) 74 | echo "JSON file created successfully...\n"; 75 | else 76 | echo "Oops! Error creating json file...\n"; 77 | 78 | # Export synonyms 79 | # https://www.algolia.com/doc/api-reference/api-methods/export-synonyms/ 80 | print("Synonyms:\n"); 81 | $synonyms = $index->browseSynonyms(); 82 | var_dump($synonyms); 83 | print("\n"); 84 | 85 | # Transform synonyms iterator to array 86 | $all_synonyms = iterator_to_array($synonyms); 87 | 88 | # Encode array to json 89 | $jsonSynonyms = json_encode($all_synonyms); 90 | 91 | # Write json to file 92 | if (file_put_contents("{$ALGOLIA_INDEX_NAME}_synonyms.json", $jsonSynonyms)) 93 | echo "JSON file created successfully...\n"; 94 | else 95 | echo "Oops! Error creating json file...\n"; 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /php/change_index_settings.php: -------------------------------------------------------------------------------- 1 | load(); 8 | 9 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 10 | # and choose a name for your index. Add these environment variables to a `.env` file: 11 | $ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; 12 | $ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; 13 | $ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; 14 | 15 | # Start the API client 16 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 17 | $client = \Algolia\AlgoliaSearch\SearchClient::create($ALGOLIA_APP_ID, $ALGOLIA_API_KEY); 18 | 19 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 20 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 21 | $index = $client->initIndex($ALGOLIA_INDEX_NAME); 22 | 23 | # Set index settings 24 | # https://www.algolia.com/doc/api-reference/api-methods/set-settings/ 25 | $index->setSettings( 26 | [ 27 | 'searchableAttributes' => ['actors', 'genre'], 28 | 'customRanking' => ['desc(rating)'], 29 | ], 30 | // Option to forward the same settings to the replica indices, when forwarding settings, please make sure your replicas already exist. 31 | [ 32 | 'forwardToReplicas' => true 33 | ] 34 | )->wait(); 35 | 36 | # Printing settings 37 | # https://www.algolia.com/doc/api-reference/api-methods/get-settings/ 38 | print("Index settings:\n"); 39 | $settings = $index->getSettings(); 40 | var_dump($settings); 41 | 42 | ?> 43 | -------------------------------------------------------------------------------- /php/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "algolia/php-quickstart", 3 | "license": "MIT", 4 | "authors": [ 5 | { 6 | "name": "Algolia", 7 | "email": "support@algolia.com" 8 | } 9 | ], 10 | "prefer-stable": true, 11 | "require": { 12 | "php": "^7.2 || ^8.0", 13 | "algolia/algoliasearch-client-php": "^3.0", 14 | "vlucas/phpdotenv": "^5.3" 15 | }, 16 | "config": { 17 | "sort-packages": true 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /php/generate_key.php: -------------------------------------------------------------------------------- 1 | load(); 12 | 13 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 14 | # and choose a name for your index. Add these environment variables to a `.env` file: 15 | $ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; 16 | $ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; 17 | $ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; 18 | 19 | # Start the API client 20 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 21 | $client = \Algolia\AlgoliaSearch\SearchClient::create($ALGOLIA_APP_ID, $ALGOLIA_API_KEY); 22 | 23 | # Set permissions for API key 24 | # https://www.algolia.com/doc/api-reference/api-methods/add-api-key/#method-param-acl 25 | $acl = ["search"]; 26 | 27 | // Set the parameters for API key 28 | // https://www.algolia.com/doc/api-reference/api-methods/add-api-key/#method-param-maxqueriesperipperhour 29 | 30 | $params = [ 31 | 'description' => 'Restricted search-only API key for algolia.com', 32 | // Rate-limit to 100 requests per hour per IP address 33 | 'maxQueriesPerIPPerHour' => 100 34 | ]; 35 | 36 | # Create a new restricted search-only API key 37 | print("Creating new key...\n"); 38 | $res = $client->addApiKey($acl, $params)->wait(); 39 | 40 | $new_key = $res['key']; 41 | 42 | if ($new_key = $res['key']) { 43 | echo "Key generated successfully: $new_key \n"; 44 | } else { 45 | echo "Error while creating key\n"; 46 | } 47 | 48 | # Test the created key 49 | print("Testing key...\n"); 50 | 51 | # Initialise a new client with the generated key 52 | $client = \Algolia\AlgoliaSearch\SearchClient::create($ALGOLIA_APP_ID, $new_key); 53 | 54 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 55 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 56 | $index = $client->initIndex($ALGOLIA_INDEX_NAME); 57 | 58 | # Test the new generated key by performing a search 59 | if ($search_res = $index->search('')) { 60 | echo "Successful key test\n"; 61 | } else { 62 | echo "Failed search with the new key\n"; 63 | } -------------------------------------------------------------------------------- /php/indexing.php: -------------------------------------------------------------------------------- 1 | load(); 7 | 8 | # Algolia client credentials 9 | $ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; 10 | $ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; 11 | $ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; 12 | 13 | # Initialize the client 14 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 15 | $client = \Algolia\AlgoliaSearch\SearchClient::create($ALGOLIA_APP_ID, $ALGOLIA_API_KEY); 16 | 17 | # Initialize an index 18 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 19 | $index = $client->initIndex($ALGOLIA_INDEX_NAME); 20 | 21 | # Define some objects to add to our index 22 | # https://www.algolia.com/doc/api-client/methods/indexing/#object-and-record 23 | $contacts = [ 24 | [ 25 | 'name' => 'Foo', 26 | 'objectID' => '1' 27 | ], 28 | [ 29 | 'name' => 'Bar', 30 | 'objectID' => '2' 31 | ] 32 | ]; 33 | 34 | # We don't have any objects (yet) in our index 35 | $res = $index->search(''); 36 | print('Current objects: '); 37 | print_r($res['hits']); 38 | print("\n"); 39 | 40 | # Save Objects: Add mutliple new objects to an index. 41 | # https://www.algolia.com/doc/api-reference/api-methods/add-objects/?client=php 42 | print('Save Objects - Adding multiple objects: '); 43 | print_r($contacts); 44 | $index->saveObjects($contacts)->wait(); 45 | 46 | $res = $index->search(''); 47 | print('Current objects: '); 48 | print_r($res['hits']); 49 | print("\n"); 50 | 51 | # Save Objects: Replace an existing object with an updated set of attributes. 52 | # https://www.algolia.com/doc/api-reference/api-methods/save-objects/?client=php 53 | print('Save Objects - Replacing objects’s attributes on: '); 54 | print_r($contacts[0]); 55 | $new_contact = [ 56 | 'name' => 'FooBar', 57 | 'objectID' => '1' 58 | ]; 59 | $index->saveObject($new_contact)->wait(); 60 | 61 | $res = $index->search(''); 62 | print('Current objects: '); 63 | print_r($res['hits']); 64 | print("\n"); 65 | 66 | # Partial Update Objects: Update one or more attributes of an existing object. 67 | # https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/?client=php 68 | print('Save Objects - Updating object’s attributes on: '); 69 | print_r($contacts[0]); 70 | $new_contact = [ 71 | 'email' => 'foo@bar.com', # New attribute 72 | 'objectID' => '1' 73 | ]; 74 | $index->partialUpdateObject($new_contact)->wait(); 75 | 76 | $res = $index->search(''); 77 | print('Current objects: '); 78 | print_r($res['hits']); 79 | print("\n"); 80 | 81 | # Delete Objects: Remove objects from an index using their objectID. 82 | # https://www.algolia.com/doc/api-reference/api-methods/delete-objects/?client=php 83 | $objectID_to_delete = $contacts[0]["objectID"]; 84 | printf('Delete Objects - Deleting object with objectID "%s"', $objectID_to_delete); 85 | $index->deleteObject($objectID_to_delete)->wait(); 86 | 87 | $res = $index->search(''); 88 | print('Current objects: '); 89 | print_r($res['hits']); 90 | print("\n"); 91 | 92 | # Replace All Objects: Clears all objects from your index and replaces them with a new set of objects. 93 | # https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/?client=php 94 | $new_contacts = [ 95 | [ 96 | 'name' => 'NewFoo', 97 | 'objectID' => '3' 98 | ], 99 | [ 100 | 'name' => 'NewBar', 101 | 'objectID' => '4' 102 | ] 103 | ]; 104 | print('Replace All Objects - Clears all objects and replaces them with: '); 105 | print_r($new_contacts); 106 | $index->replaceAllObjects($new_contacts)->wait(); 107 | 108 | $res = $index->search(''); 109 | print('Current objects: '); 110 | print_r($res['hits']); 111 | print("\n"); 112 | 113 | # Delete By: Remove all objects matching a filter (including geo filters). 114 | # https://www.algolia.com/doc/api-reference/api-methods/delete-by/?client=php 115 | print_r('Delete By - Remove all objects matching "name:NewBar"'); 116 | 117 | # Firstly, have an attribute to filter on 118 | # https://www.algolia.com/doc/api-client/methods/settings/?client=php 119 | $index->setSettings([ 120 | 'attributesForFaceting' => ['name'] 121 | ])->wait(); 122 | 123 | $index->deleteBy([ 124 | 'facetFilters' => ['name:NewBar'] # https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ 125 | ])->wait(); 126 | 127 | $res = $index->search(''); 128 | print('Current objects: '); 129 | print_r($res['hits']); 130 | print("\n"); 131 | 132 | # Get Objects: Get one or more objects using their objectIDs. 133 | # https://www.algolia.com/doc/api-reference/api-methods/get-objects/?client=php 134 | $object_id = $new_contacts[0]['objectID']; 135 | printf('Get Objects - Getting object with objectID "%s"', $object_id); 136 | 137 | $res = $index->getObject($object_id); 138 | print('Results: '); 139 | print_r($res); 140 | print("\n"); 141 | 142 | # Custom Batch: Perform several indexing operations in one API call. 143 | # https://www.algolia.com/doc/api-reference/api-methods/batch/?client=php 144 | $operations = [ 145 | [ 146 | 'action' => 'addObject', 147 | 'indexName' => $ALGOLIA_INDEX_NAME, 148 | 'body' => [ 149 | 'name' => 'BatchedBar', 150 | ] 151 | ], 152 | [ 153 | 'action' => 'updateObject', 154 | 'indexName' => $ALGOLIA_INDEX_NAME, 155 | 'body' => [ 156 | 'objectID' => $object_id, 157 | 'name' => 'NewBatchedBar', 158 | ] 159 | ] 160 | ]; 161 | print('Custom Batch - Batching the operations: '); 162 | print_r( $operations); 163 | $res = $client->multipleBatch($operations)->wait(); 164 | 165 | $res = $index->search(''); 166 | print('Current objects: '); 167 | print_r($res['hits']); 168 | print("\n"); 169 | 170 | 171 | # Clear Objects: Clear the records of an index without affecting its settings. 172 | # https://www.algolia.com/doc/api-reference/api-methods/clear-objects/?client=php 173 | print_r("Clear Objects: Clear the records of an index without affecting its settings.\n"); 174 | $index->clearObjects()->wait(); 175 | 176 | # We don't have any objects in our index 177 | $res = $index->search(''); 178 | print('Current objects: '); 179 | print_r($res['hits']); -------------------------------------------------------------------------------- /php/rest_api_return_top_hits.php: -------------------------------------------------------------------------------- 1 | load(); 11 | 12 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 13 | # and choose a name for your index. Add these environment variables to a `.env` file: 14 | $ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; 15 | $ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; 16 | $ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; 17 | 18 | # The Analytics API can be reached from multiple domains, each specific to a region. 19 | # You should use the domain that matches the region where your analytics data is stored and processed. 20 | # View your analytics region: https://www.algolia.com/infra/analytics 21 | # The following domains are available: 22 | # United States: https://analytics.us.algolia.com 23 | # Europe (Germany): https://analytics.de.algolia.com 24 | 25 | $URL_DOMAIN = $_ENV['URL_DOMAIN']; 26 | 27 | $url = "$URL_DOMAIN/2/searches?index=$ALGOLIA_INDEX_NAME&limit=1000"; 28 | 29 | # Describing HTTP request 30 | $request_options = [ 31 | 'http' => [ 32 | 'method' => 'GET', 33 | 'header' => join("\r\n", [ 34 | "X-Algolia-Application-Id: $ALGOLIA_APP_ID", 35 | "X-Algolia-API-Key: $ALGOLIA_API_KEY", 36 | ]), 37 | ] 38 | ]; 39 | 40 | # Sending HTTP request 41 | $result = file_get_contents($url, false, stream_context_create($request_options)); 42 | 43 | if ($result === FALSE) { 44 | exit("Failed HTTP request"); 45 | } 46 | 47 | # Returning 1000 Top Searches 48 | print("1000 Top Searches:\n"); 49 | var_dump($result); 50 | 51 | # Format the resulting json string 52 | $json = json_decode($result); 53 | $formatted_result = json_encode($json, JSON_PRETTY_PRINT); 54 | 55 | # Write json to file 56 | if (file_put_contents("{$ALGOLIA_INDEX_NAME}_top_1000_searches.json", $formatted_result)) 57 | echo "JSON file created successfully...\n"; 58 | else 59 | echo "Oops! Error creating json file...\n"; 60 | -------------------------------------------------------------------------------- /php/restore.php: -------------------------------------------------------------------------------- 1 | load(); 8 | 9 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 10 | # and choose a name for your index. Add these environment variables to a `.env` file: 11 | $ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; 12 | $ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; 13 | $ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; 14 | 15 | # Start the API client 16 | # https://www.algolia.com/doc/api-client/getting-started/initialize/php/?client=php#initialize-the-search-client 17 | $client = \Algolia\AlgoliaSearch\SearchClient::create($ALGOLIA_APP_ID, $ALGOLIA_API_KEY); 18 | 19 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 20 | # https://www.algolia.com/doc/api-client/getting-started/initialize/php/?client=php#initialize-the-search-client 21 | $index = $client->initIndex($ALGOLIA_INDEX_NAME); 22 | 23 | # Restoring all records with replace all objects method 24 | # https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/ 25 | 26 | # Read json file 27 | $jsonRecords = file_get_contents("{$ALGOLIA_INDEX_NAME}_records.json"); 28 | print("All the records:"); 29 | var_dump($jsonRecords); 30 | print("\n"); 31 | 32 | # Decode json file 33 | $arrayRecords = json_decode($jsonRecords, true); 34 | 35 | # Restore Records 36 | $index->replaceAllObjects($arrayRecords); 37 | print("Records restored\n"); 38 | 39 | # Restoring settings with set settings method 40 | # https://www.algolia.com/doc/api-reference/api-methods/set-settings/ 41 | 42 | # Read json file 43 | $jsonSettings = file_get_contents("{$ALGOLIA_INDEX_NAME}_settings.json"); 44 | print("Index settings:\n"); 45 | var_dump($jsonSettings); 46 | print("\n"); 47 | 48 | # Decode json file 49 | $settings = json_decode($jsonSettings, true); 50 | 51 | # Restore settings 52 | $index->setSettings($settings); 53 | print("Settings restored\n"); 54 | 55 | # Restoring Rules with replace all rules method 56 | # https://www.algolia.com/doc/api-reference/api-methods/replace-all-rules/ 57 | 58 | # Read json file 59 | $jsonRules = file_get_contents("{$ALGOLIA_INDEX_NAME}_rules.json"); 60 | print("Rules:\n"); 61 | var_dump($jsonRules); 62 | print("\n"); 63 | 64 | # Decode json file 65 | $arrayRules = json_decode($jsonRules, true); 66 | 67 | # Restore Rules 68 | $index->replaceAllRules($arrayRules); 69 | print("Rules restored\n"); 70 | 71 | 72 | # Restoring Synonyms with replace all synonyms method 73 | # https://www.algolia.com/doc/api-reference/api-methods/replace-all-synonyms/?client=php 74 | 75 | # Read json file 76 | $jsonSynonyms = file_get_contents("{$ALGOLIA_INDEX_NAME}_synonyms.json"); 77 | print("Synonyms:\n"); 78 | var_dump($jsonSynonyms); 79 | print("\n"); 80 | 81 | # Decode json file 82 | $arraySynonyms = json_decode($jsonSynonyms, true); 83 | 84 | # Restore Synonyms 85 | $index->replaceAllSynonyms($arraySynonyms); 86 | print("Synonyms restored\n"); -------------------------------------------------------------------------------- /php/rules.php: -------------------------------------------------------------------------------- 1 | load(); 8 | 9 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 10 | # and choose a name for your index. Add these environment variables to a `.env` file: 11 | $ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; 12 | $ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; 13 | $ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; 14 | 15 | # Start the API client 16 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 17 | $client = \Algolia\AlgoliaSearch\SearchClient::create($ALGOLIA_APP_ID, $ALGOLIA_API_KEY); 18 | 19 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 20 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 21 | $index = $client->initIndex($ALGOLIA_INDEX_NAME); 22 | 23 | # Exporting the rules 24 | # https://www.algolia.com/doc/api-reference/api-methods/export-rules/#examples 25 | print("Original rules:\n"); 26 | $iterator = $index->browseRules(); 27 | foreach ($iterator as $rule) { 28 | var_dump($rule); 29 | } 30 | print("\n"); 31 | 32 | # Adding a new rule 33 | # https://www.algolia.com/doc/api-reference/api-methods/save-rule/#save-a-rule 34 | $object_id = 'a-rule-id'; 35 | print("Adding a new rule called: $object_id\n"); 36 | $rule = array( 37 | 'objectID' => $object_id, 38 | 'conditions' => array(array( 39 | 'pattern' => 'flower', 40 | 'anchoring' => 'contains', 41 | )), 42 | 'consequence' => array( 43 | 'promote' => array(array( 44 | 'objectID' => '439957720', 45 | 'position' => 0, 46 | )) 47 | ) 48 | ); 49 | $index->saveRule($rule)->wait(); 50 | 51 | # Exporting the modified rules 52 | # https://www.algolia.com/doc/api-reference/api-methods/export-rules/#examples 53 | print("Modified rules:\n"); 54 | $iterator = $index->browseRules(); 55 | foreach ($iterator as $rule) { 56 | var_dump($rule); 57 | } 58 | print("\n"); 59 | 60 | ?> 61 | -------------------------------------------------------------------------------- /php/simple.php: -------------------------------------------------------------------------------- 1 | load(); 8 | 9 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 10 | # and choose a name for your index. Add these environment variables to a `.env` file: 11 | $ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; 12 | $ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; 13 | $ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; 14 | 15 | # Start the API client 16 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 17 | $client = \Algolia\AlgoliaSearch\SearchClient::create($ALGOLIA_APP_ID, $ALGOLIA_API_KEY); 18 | 19 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 20 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 21 | $index = $client->initIndex($ALGOLIA_INDEX_NAME); 22 | 23 | # Add new objects to the index 24 | # https://www.algolia.com/doc/api-reference/api-methods/add-objects/ 25 | $newObject = ['objectID' => 1, 'name' => 'Foo']; 26 | $res = $index->saveObjects([$newObject]); 27 | 28 | # Wait for the indexing task to complete 29 | # https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 30 | $res->wait(); 31 | 32 | # Search the index for "Fo" 33 | # https://www.algolia.com/doc/api-reference/api-methods/search/ 34 | $objects = $index->search('Fo'); 35 | print_r($objects); 36 | -------------------------------------------------------------------------------- /python/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.11, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.11-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster 2 | ARG VARIANT=3-bullseye 3 | FROM mcr.microsoft.com/vscode/devcontainers/python:${VARIANT} 4 | 5 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 6 | ARG NODE_VERSION="none" 7 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 8 | 9 | # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. 10 | # COPY requirements.txt /tmp/pip-tmp/ 11 | # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ 12 | # && rm -rf /tmp/pip-tmp 13 | 14 | # [Optional] Uncomment this section to install additional OS packages. 15 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 16 | # && apt-get -y install --no-install-recommends 17 | 18 | # [Optional] Uncomment this line to install global node packages. 19 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /python/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Python 3", 3 | "runArgs": ["--init"], 4 | "build": { 5 | "dockerfile": "Dockerfile", 6 | "args": { 7 | // Update 'VARIANT' to pick a Python version: 3, 3.11, 3.10, 3.9, 3.8, 3.7, 3.6. 8 | // Append -bullseye or -buster to pin to an OS version. 9 | // Use -bullseye variants on local on arm64/Apple Silicon. 10 | "VARIANT": "3-bullseye", 11 | // Options 12 | "NODE_VERSION": "lts/*" 13 | } 14 | }, 15 | 16 | // Set *default* container specific settings.json values on container create. 17 | "settings": { 18 | "python.pythonPath": "/usr/local/bin/python", 19 | "python.languageServer": "Pylance", 20 | "python.linting.enabled": true, 21 | "python.linting.pylintEnabled": true, 22 | "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", 23 | "python.formatting.blackPath": "/usr/local/py-utils/bin/black", 24 | "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", 25 | "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", 26 | "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", 27 | "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", 28 | "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", 29 | "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", 30 | "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint" 31 | }, 32 | 33 | // Add the IDs of extensions you want installed when the container is created. 34 | "extensions": [ 35 | "ms-python.python", 36 | "ms-python.vscode-pylance" 37 | ], 38 | 39 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 40 | // "forwardPorts": [], 41 | 42 | // Use 'postCreateCommand' to run commands after the container is created. 43 | // "postCreateCommand": "pip3 install --user -r requirements.txt", 44 | 45 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 46 | "remoteUser": "vscode", 47 | "postStartCommand": "pip install --user -r requirements.txt", 48 | } -------------------------------------------------------------------------------- /python/.env.example: -------------------------------------------------------------------------------- 1 | ALGOLIA_APP_ID= 2 | ALGOLIA_API_KEY= 3 | ALGOLIA_INDEX_NAME= 4 | ALGOLIA_ANALYTICS_DOMAIN="https://analytics.us.algolia.com" 5 | # Read more about analytics domains here: https://www.algolia.com/doc/rest-api/analytics/ 6 | -------------------------------------------------------------------------------- /python/README.md: -------------------------------------------------------------------------------- 1 | # API Clients Quickstarts: Python 2 | 3 | This quickstart demonstrates various usages of the the [Algolia Python API Client](https://www.algolia.com/doc/api-client/getting-started/install/python/?client=python). 4 | 5 | ## Setting up the quickstart 6 | 7 | ### Prerequisites 8 | 9 | - An Algolia account. If you don't have one already, [create an account for free](https://www.algolia.com/users/sign_up). 10 | - A Python >= 3.7 local environment, or [Docker](https://www.docker.com/get-started). 11 | 12 |
13 | Using VSCode 14 | 15 | By using VScode and having the [Visual Studio Code Remote - Containers](https://code.visualstudio.com/docs/remote/containers) extension installed, you can run any of the quickstarts by using the command [Remote-Containers: Open Folder in Container](https://code.visualstudio.com/docs/remote/containers#_quick-start-open-an-existing-folder-in-a-container) command. 16 | 17 | Each of the quickstart contains a [.devcontainer.json](./.devcontainer/devcontainer.json), along with a [Dockerfile](./.devcontainer/Dockerfile). 18 |
19 | 20 | 1. Create an Algolia Application and an [Algolia Index](https://www.algolia.com/doc/guides/getting-started/quick-start/tutorials/getting-started-with-the-dashboard/#indices) 21 | 2. Copy the file [.env.example](.env.example) and rename it to `.env` 22 | 3. Set the environment variables `ALGOLIA_APP_ID`, `ALGOLIA_API_KEY` and `ALGOLIA_INDEX_NAME` in the `.env` file. You can obtain those from the [Algolia Dashboard](https://www.algolia.com/api-keys/). The `ALGOLIA_API_KEY` should be the "Admin API Key" (necessary for indexing). 23 | 24 | ## How to use 25 | 26 | Once setup, you can run each of the script in this folder using the Python command line. 27 | Example: to execute the `simple.py` script: 28 | 29 | ```bash 30 | python simple.py 31 | ``` 32 | 33 | ## Available quickstarts 34 | 35 | | File | Description | 36 | | ------------- | ------------- | 37 | | [simple.py](./simple.py) | Index a single object and run a search query | 38 | | [indexing.py](./indexing.py) | Showcase of the main indexing methods | 39 | | [generate_key.py](./generate_key.py) | Generate a rate limited API key | 40 | | [backup.py](./backup.py) | Backup an index and associated rules, synonyms and settings | 41 | | [restore.py](./restore.py) | Restore an index from a local file | 42 | | [analytics.py](./analytics.py) | Retrieve top 1000 searches for an index | 43 | -------------------------------------------------------------------------------- /python/analytics-backup.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Analytics Backup - Retrieve the last 7 days of analytics data 3 | 4 | This script fetches data from the Analytics REST API - https://www.algolia.com/doc/rest-api/analytics/ and writes it with a 5 | timestamp to a local file. Analytics data is only available via the Dashboard for a maximum 365 days, so this script allows users 6 | to backup their data. 7 | 8 | There is no API client for Analytics, so this script uses the Python Requests library to make the call. 9 | ''' 10 | 11 | import json 12 | from datetime import datetime 13 | from os import getenv 14 | 15 | import requests 16 | from dotenv import find_dotenv, load_dotenv 17 | 18 | load_dotenv(find_dotenv()) 19 | 20 | # Get and set the current timestamp 21 | now = datetime.now() 22 | timestamp = now.strftime("%Y-%m-%d_%H:%M:%S") 23 | 24 | # Get your Algolia Application ID, (analytics) API key, and Index name from the dashboard: https://www.algolia.com/account/api-keys 25 | # Get your Algolia analytics region here: https://www.algolia.com/infra/analytics 26 | # Read more about analytics domains here: https://www.algolia.com/doc/rest-api/analytics/ 27 | # Add these environment variables to a `.env` file (you can use the .env.example file as a template). 28 | ALGOLIA_APP_ID = getenv('ALGOLIA_APP_ID') 29 | ALGOLIA_API_KEY = getenv('ALGOLIA_API_KEY') 30 | ALGOLIA_INDEX_NAME = getenv('ALGOLIA_INDEX_NAME') 31 | ANALYTICS_DOMAIN = getenv('ALGOLIA_ANALYTICS_DOMAIN') 32 | 33 | # Initialise requests session 34 | client = requests.Session() 35 | 36 | # Set required session headers 37 | client.headers = {"X-Algolia-API-Key": ALGOLIA_API_KEY, "X-Algolia-Application-Id": ALGOLIA_APP_ID} 38 | 39 | # Set the index and limit parameters. You can also set params for startDate, endDate, orderBy and more - https://www.algolia.com/doc/rest-api/analytics/#get-top-searches 40 | params = {'index': {ALGOLIA_INDEX_NAME}, 'limit': 100} 41 | 42 | 43 | # Create a function to validate date inputs 44 | def validate(date_string): 45 | try: 46 | if date_string != datetime.strptime(date_string, "%Y-%m-%d").strftime('%Y-%m-%d'): 47 | raise ValueError 48 | return True 49 | except ValueError: 50 | print("Incorrect date format.") 51 | return False 52 | 53 | 54 | # Create a function to handle the API calls. 55 | # If there is an error querying an endpoint, the script will continue but the value for that metric will be null. 56 | def make_request(endpoint, metric, start_date='', end_date=''): 57 | try: 58 | if not start_date: 59 | response = client.request("GET", f'{ANALYTICS_DOMAIN}/2/{endpoint}', params=params) 60 | else: 61 | params["startDate"] = start_date 62 | params["endDate"] = end_date 63 | response = client.request("GET", f'{ANALYTICS_DOMAIN}/2/{endpoint}', params=params) 64 | 65 | if response.status_code != 200: 66 | print(f'Problem with {endpoint} request: {response.status_code}. No data collected.') 67 | return 68 | 69 | data = response.json() 70 | 71 | return data[metric] 72 | except: 73 | print(f'Could not complete analytics retrieval for {endpoint, metric}') 74 | 75 | 76 | # Ask the user whether they want to enter a custom date range for analytics retrieval. 77 | # NOTE: There is a limit to the period that analytics data is held for. Either 90 or 360 days, depending on your plan. 78 | # The script will except start dates before the beginning of your analytics retention period. 79 | custom_date_range = input('Default date range is last 7 days. Do you want to enter a custom date range for analytics retrieval? (Y/N): ').lower() 80 | 81 | while custom_date_range not in ['y', 'n', 'yes', 'no']: 82 | custom_date_range = input('Default date range is last 7 days. Do you want to enter a custom date range for analytics retrieval? (Y/N): ').lower() 83 | 84 | # Ask the user for their required start and end dates. 85 | if custom_date_range in ['y', 'yes']: 86 | start_date = input('Enter start date for analytics retrieval (YYYY-MM-DD): ') 87 | while not validate(start_date): 88 | start_date = input('Enter start date for analytics retrieval (YYYY-MM-DD): ') 89 | 90 | end_date = input('Enter end date for analytics retrieval (YYYY-MM-DD): ') 91 | while not validate(end_date): 92 | end_date = input('Enter end date for analytics retrieval (YYYY-MM-DD): ') 93 | 94 | date_params = {'start_date': start_date, 'end_date': end_date} 95 | else: 96 | date_params = {} 97 | 98 | # Create an array for API endpoints and the metric we want to target from each. 99 | queries = [ 100 | {'endpoint': 'searches', 'metric': 'searches'}, 101 | {'endpoint': 'searches/count', 'metric': 'count'}, 102 | {'endpoint': 'searches/noResults', 'metric': 'searches'}, 103 | {'endpoint': 'users/count', 'metric': 'count'}, 104 | {'endpoint': 'hits', 'metric': 'hits'}, 105 | {'endpoint': 'searches/noResultRate', 'metric': 'rate'}, 106 | {'endpoint': 'searches/noClickRate', 'metric': 'rate'} 107 | ] 108 | 109 | # Make the requests and create an object with the results. 110 | print('Retrieving analytics data...') 111 | results = {query['endpoint']: make_request(query['endpoint'], query['metric'], **date_params) for query in queries} 112 | print('Analytics data retrieved') 113 | # Define the object structure that will be output to JSON 114 | output = { 115 | timestamp: { 116 | "top_searches": results['searches'], 117 | "total_searches": results['searches/count'], 118 | "searches_without_results": results['searches/noResults'], 119 | "total_users": results['users/count'], 120 | "top_results": results['hits'], 121 | "no_results_rate": results['searches/noResultRate'], 122 | "no_clicks_rate": results['searches/noClickRate'], 123 | "date_range": date_params if date_params else 'Last 7 days' 124 | } 125 | } 126 | 127 | # Create a JSON file with the analytics data 128 | print("Creating output...") 129 | filename = f'{ALGOLIA_INDEX_NAME}_analytics_{timestamp}.json' 130 | try: 131 | with open(filename, 'w') as file: 132 | json.dump(output, file) 133 | print(f'Output file - {filename} - created.') 134 | except Exception: 135 | raise Exception ('Error creating json file.') 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /python/analytics.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Analytics API Query 3 | 4 | This script makes a GET request to the /searches endpoint on the Analytics REST API - https://www.algolia.com/doc/rest-api/analytics/. 5 | To get the top 1000 searches over the last 7 days. 6 | 7 | There is no API client for Analytics, so this script uses the Python Requests library to make the call. 8 | ''' 9 | 10 | import requests 11 | import csv 12 | from os import getenv 13 | 14 | from dotenv import find_dotenv, load_dotenv 15 | 16 | load_dotenv(find_dotenv()) 17 | 18 | # Get your Algolia Application ID, (analytics) API key, and Index name from the dashboard: https://www.algolia.com/account/api-keys 19 | # Get your Algolia analytics domain here: https://www.algolia.com/infra/analytics 20 | # Add these environment variables to a `.env` file: 21 | ALGOLIA_APP_ID = getenv('ALGOLIA_APP_ID') 22 | ALGOLIA_API_KEY = getenv('ALGOLIA_API_KEY') 23 | ALGOLIA_INDEX_NAME = getenv('ALGOLIA_INDEX_NAME') 24 | ANALYTICS_DOMAIN = getenv('ALGOLIA_ANALYTICS_DOMAIN') 25 | 26 | # Initialise requests session 27 | client = requests.Session() 28 | 29 | # Set required session headers 30 | client.headers = {"X-Algolia-API-Key": ALGOLIA_API_KEY, "X-Algolia-Application-Id": ALGOLIA_APP_ID} 31 | 32 | # Set the index and limit parameters. You can also set params for startDate, endDate, orderBy and more - https://www.algolia.com/doc/rest-api/analytics/#get-top-searches 33 | params = {'index': {ALGOLIA_INDEX_NAME}, 'limit': 1000} 34 | 35 | # Make the call to the analytics endpoint 36 | print('Fetching analytics data...') 37 | try: 38 | response = client.request("GET", f'{ANALYTICS_DOMAIN}/2/searches', params=params) 39 | except requests.RequestException: 40 | raise 41 | 42 | if response.status_code != 200: 43 | print(f'Problem with request: {response.status_code}. Exiting.') 44 | exit() 45 | 46 | print('Analytics data retrieved.') 47 | 48 | content = response.json() 49 | searches = content['searches'] 50 | 51 | print('Creating CSV file...') 52 | 53 | # Create a csv file with the data 54 | try: 55 | keys = searches[0].keys() 56 | with open(f'{ALGOLIA_INDEX_NAME}_top_1000_searches.csv', 'w') as f: 57 | dict_writer = csv.DictWriter(f, keys, lineterminator='\n') 58 | dict_writer.writeheader() 59 | dict_writer.writerows(searches) 60 | except Exception: 61 | print('Error creating csv file.') 62 | exit() 63 | 64 | print(f'CSV file "{ALGOLIA_INDEX_NAME}_top_1000_searches.csv" created.') -------------------------------------------------------------------------------- /python/backup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Backup Index 3 | 4 | This script will export an index, including any settings, rules and synonyms. 5 | 6 | It can be used in conjunction with restore.py to backup and restore an index to an application. 7 | 8 | """ 9 | 10 | import json 11 | import os.path 12 | from os import getenv 13 | 14 | # Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/python/?client=python 15 | from algoliasearch.search_client import SearchClient 16 | from dotenv import find_dotenv, load_dotenv 17 | 18 | load_dotenv(find_dotenv()) 19 | 20 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 21 | # and choose a name for your index. Add these environment variables to a `.env` file: 22 | ALGOLIA_APP_ID = getenv('ALGOLIA_APP_ID') 23 | ALGOLIA_API_KEY = getenv('ALGOLIA_API_KEY') 24 | ALGOLIA_INDEX_NAME = getenv('ALGOLIA_INDEX_NAME') 25 | 26 | # Set the path for the current file, we'll need this when generating the exports 27 | current_path = os.path.dirname(os.path.abspath(__file__)) 28 | 29 | # Start the API client 30 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 31 | client = SearchClient.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 32 | 33 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 34 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 35 | index = client.init_index(ALGOLIA_INDEX_NAME) 36 | 37 | # Initialise lists to store the exported data 38 | records, settings, rules, synonyms = [], [], [], [] 39 | 40 | # Get the index records and any associated rules, settings, and synonyms. 41 | try: 42 | # Get all the records from the index and store them in a list 43 | print('Retrieving records...') 44 | records = list(index.browse_objects()) 45 | print(f'{len(records)} records retrieved.') 46 | 47 | # Get the settings for the index 48 | print('Retrieving settings...') 49 | settings = index.get_settings() 50 | print('Settings retrieved.') 51 | 52 | # Get the rules for the index 53 | print('Retrieving rules...') 54 | rules = list(index.browse_rules()) 55 | print(f'{str(len(rules))} rules retrieved.') 56 | 57 | # Get the synonyms for the index 58 | print('Retrieving synonyms...') 59 | synonyms = list(index.browse_synonyms()) 60 | print(f'{str(len(synonyms))} synonyms retrieved.') 61 | except Exception as e: 62 | print(f'Error retrieving data: {e}') 63 | exit() 64 | 65 | # Create a function to help with writing the output data 66 | def create_json(data, name, path): 67 | ''' 68 | Converts a list to a json file 69 | ''' 70 | if data: 71 | json_data = json.dumps(data) 72 | with open(f'{path}/{ALGOLIA_INDEX_NAME}_{name}.json', 'w', encoding='utf-16') as file: 73 | file.write(json_data) 74 | 75 | # Write the exported data to output files 76 | print('Exporting data...') 77 | try: 78 | create_json(records, 'index', current_path) 79 | print('Exported index.') 80 | create_json(settings, 'settings', current_path) 81 | print('Exported settings.') 82 | create_json(rules, 'rules', current_path) 83 | print('Exported rules.') 84 | create_json(synonyms, 'synonyms', current_path) 85 | print('Exported synonyms.') 86 | print('Data exported successfully.') 87 | except Exception as e: 88 | print(f'Error exporting data: {e}') 89 | exit() 90 | -------------------------------------------------------------------------------- /python/generate_key.py: -------------------------------------------------------------------------------- 1 | """ 2 | API Key Generator 3 | 4 | This script will generate an API key for an Algolia application. 5 | 6 | The generated key will be valid for Search operations, and will be limited to 100 queries per hour. 7 | 8 | """ 9 | 10 | from os import getenv 11 | 12 | # Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/python/?client=python 13 | from algoliasearch.search_client import SearchClient 14 | from dotenv import find_dotenv, load_dotenv 15 | 16 | load_dotenv(find_dotenv()) 17 | 18 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 19 | # and choose a name for your index. Add these environment variables to a `.env` file: 20 | ALGOLIA_APP_ID = getenv('ALGOLIA_APP_ID') 21 | ALGOLIA_API_KEY = getenv('ALGOLIA_API_KEY') 22 | ALGOLIA_INDEX_NAME = getenv('ALGOLIA_INDEX_NAME') 23 | 24 | # Start the API client 25 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 26 | client = SearchClient.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 27 | 28 | # Create the key 29 | #https://www.algolia.com/doc/api-reference/api-methods/add-api-key/?client=python 30 | 31 | # Set the permissions for the key 32 | acl = ['search'] 33 | 34 | # Set the parameters for the key 35 | params = { 36 | 'description': 'Restricted search-only API key for algolia.com', 37 | # Rate-limit to 100 requests per hour per IP address 38 | 'maxQueriesPerIPPerHour': 100 39 | } 40 | 41 | # Make the API request to add the key 42 | print('Generating key...') 43 | try: 44 | res = client.add_api_key(acl, params).wait() 45 | key = res['key'] 46 | print(f'Key generated successfully: {key}.') 47 | except Exception as e: 48 | print(f'Error generating key: {e}') 49 | exit() 50 | 51 | # Test the created key 52 | print('Testing key...') 53 | 54 | # Initialise a new client with the generated key 55 | client = SearchClient.create(ALGOLIA_APP_ID, key) 56 | 57 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 58 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 59 | index = client.init_index(ALGOLIA_INDEX_NAME) 60 | 61 | try: 62 | res = index.search('') 63 | if res: 64 | print('Key tested successfully') 65 | except Exception as e: 66 | print(f'Error testing key: {e}') 67 | exit() 68 | 69 | -------------------------------------------------------------------------------- /python/indexing.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | 3 | 4 | from algoliasearch.search_client import SearchClient 5 | from dotenv import load_dotenv, find_dotenv 6 | 7 | load_dotenv(find_dotenv()) 8 | 9 | # Algolia client credentials 10 | ALGOLIA_APP_ID = getenv('ALGOLIA_APP_ID') 11 | ALGOLIA_API_KEY = getenv('ALGOLIA_API_KEY') 12 | ALGOLIA_INDEX_NAME = getenv('ALGOLIA_INDEX_NAME') 13 | 14 | # Initialize the client 15 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/?client=python 16 | client = SearchClient.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 17 | 18 | # Initialize an index 19 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 20 | index = client.init_index(ALGOLIA_INDEX_NAME) 21 | 22 | # Define some objects to add to our index 23 | # https://www.algolia.com/doc/api-client/methods/indexing/#object-and-record 24 | contacts = [ 25 | { 26 | 'name': 'Foo', 27 | 'objectID': '1' 28 | }, 29 | { 30 | 'name': 'Bar', 31 | 'objectID': '2' 32 | } 33 | ] 34 | 35 | # We don't have any objects (yet) in our index 36 | res = index.search('') 37 | print('Current objects: ', res['hits']) 38 | 39 | # Save Objects: Add mutliple new objects to an index. 40 | # https://www.algolia.com/doc/api-reference/api-methods/add-objects/?client=python 41 | print('Save Objects - Adding multiple objects: ', contacts) 42 | index.save_objects(contacts).wait() 43 | 44 | res = index.search('') 45 | print('Current objects: ', res['hits'], '\n') 46 | 47 | # Save Objects: Replace an existing object with an updated set of attributes. 48 | # https://www.algolia.com/doc/api-reference/api-methods/save-objects/?client=python 49 | print(f'Save Objects - Replacing objects’s attributes on {contacts[0]}') 50 | new_contact = { 51 | 'name': 'FooBar', 52 | 'objectID': '1' 53 | } 54 | index.save_object(new_contact).wait() 55 | 56 | res = index.search('') 57 | print('Current objects: ', res['hits'], '\n') 58 | 59 | # Partial Update Objects: Update one or more attributes of an existing object. 60 | # https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/?client=python 61 | print(f'Save Objects - Updating object’s attributes on {contacts[0]}') 62 | new_contact = { 63 | 'email': 'foo@bar.com', # New attribute 64 | 'objectID': '1' 65 | } 66 | index.partial_update_object(new_contact).wait() 67 | 68 | res = index.search('') 69 | print('Current objects: ', res['hits'], '\n') 70 | 71 | # Delete Objects: Remove objects from an index using their objectID. 72 | # https://www.algolia.com/doc/api-reference/api-methods/delete-objects/?client=python 73 | objectID_to_delete = contacts[0]["objectID"] 74 | print(f'Delete Objects - Deleting object with objectID "{objectID_to_delete}"') 75 | index.delete_object(objectID_to_delete).wait() 76 | 77 | res = index.search('') 78 | print('Current objects: ', res['hits'], '\n') 79 | 80 | # Replace All Objects: Clears all objects from your index and replaces them with a new set of objects. 81 | # https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/?client=python 82 | new_contacts = [ 83 | { 84 | 'name': 'NewFoo', 85 | 'objectID': '3' 86 | }, 87 | { 88 | 'name': 'NewBar', 89 | 'objectID': '4' 90 | } 91 | ] 92 | print(f'Replace All Objects - Clears all objects and replaces them with "{new_contacts}"') 93 | index.replace_all_objects(new_contacts).wait() 94 | 95 | res = index.search('') 96 | print('Current objects: ', res['hits'], '\n') 97 | 98 | # Delete By: Remove all objects matching a filter (including geo filters). 99 | # https://www.algolia.com/doc/api-reference/api-methods/delete-by/?client=python 100 | print(f'Delete By - Remove all objects matching "name:NewBar"') 101 | 102 | # Firstly, have an attribute to filter on 103 | # https://www.algolia.com/doc/api-client/methods/settings/?client=python 104 | index.set_settings({ 105 | 'attributesForFaceting': ['name'] 106 | }).wait() 107 | 108 | index.delete_by({ 109 | 'facetFilters': [f'name:NewBar'] # https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ 110 | }).wait() 111 | 112 | res = index.search('') 113 | print('Current objects: ', res['hits'], '\n') 114 | 115 | # Get Objects: Get one or more objects using their objectIDs. 116 | # https://www.algolia.com/doc/api-reference/api-methods/get-objects/?client=python 117 | object_id = new_contacts[0]['objectID'] 118 | print(f'Get Objects - Getting object with objectID "{object_id}"') 119 | 120 | res = index.get_object(object_id) 121 | print('Results: ', res, '\n') 122 | 123 | # Custom Batch: Perform several indexing operations in one API call. 124 | # https://www.algolia.com/doc/api-reference/api-methods/batch/?client=python 125 | operations = [ 126 | { 127 | 'action': 'addObject', 128 | 'indexName': ALGOLIA_INDEX_NAME, 129 | 'body': { 130 | 'name': 'BatchedBar', 131 | } 132 | }, 133 | { 134 | 'action': 'updateObject', 135 | 'indexName': ALGOLIA_INDEX_NAME, 136 | 'body': { 137 | 'objectID': object_id, 138 | 'name': 'NewBatchedBar', 139 | } 140 | } 141 | ] 142 | print(f'Custom Batch - Batching {len(operations)} operations') 143 | res = client.multiple_batch(operations).wait() 144 | 145 | res = index.search('') 146 | print('Current objects: ', res['hits'], '\n') 147 | 148 | 149 | # Clear Objects: Clear the records of an index without affecting its settings. 150 | # https://www.algolia.com/doc/api-reference/api-methods/clear-objects/?client=python 151 | print('Clear Objects: Clear the records of an index without affecting its settings.') 152 | index.clear_objects().wait() 153 | 154 | # We don't have any objects in our index 155 | res = index.search('') 156 | print('Current objects: ', res['hits']) 157 | -------------------------------------------------------------------------------- /python/requirements.txt: -------------------------------------------------------------------------------- 1 | algoliasearch>=3.0,<4.0 2 | python-dotenv==0.17.1 -------------------------------------------------------------------------------- /python/restore.py: -------------------------------------------------------------------------------- 1 | """ 2 | Restore Index 3 | 4 | This script will restore an index, including any settings, rules and synonyms. 5 | 6 | It can be used in conjuction with backup.py to backup and restore an index to an application. 7 | 8 | When run, the user will be prompted to enter an index name. The script will look for files prefixed 9 | with this index name to use for the restore. E.g. if the index name is 'my-index', the script will 10 | look for 'my-index_index.json', 'my-index_rules.json', 'my-index_settings.json' and 11 | 'my-index_synonyms.json' files in the same directory. 12 | 13 | This script will overwrite any existing indexes with the same name. 14 | 15 | """ 16 | 17 | import json 18 | import os.path 19 | from os import getenv 20 | 21 | # Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/python/?client=python 22 | from algoliasearch.search_client import SearchClient 23 | from dotenv import find_dotenv, load_dotenv 24 | 25 | load_dotenv(find_dotenv()) 26 | 27 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 28 | # and choose a name for your index. Add these environment variables to a `.env` file: 29 | ALGOLIA_APP_ID = getenv('ALGOLIA_APP_ID') 30 | ALGOLIA_API_KEY = getenv('ALGOLIA_API_KEY') 31 | ALGOLIA_INDEX_NAME = input('Enter index name: ') 32 | 33 | # Start the API client 34 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 35 | client = SearchClient.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 36 | 37 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 38 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 39 | index = client.init_index(ALGOLIA_INDEX_NAME) 40 | 41 | # Check to see which files are available for restoration. There must be at least an index file. 42 | current_path = os.path.dirname(os.path.abspath(__file__)) 43 | 44 | is_index_file = os.path.isfile(f'{current_path}/{ALGOLIA_INDEX_NAME}_index.json') 45 | is_settings_file = os.path.isfile(f'{current_path}/{ALGOLIA_INDEX_NAME}_settings.json') 46 | is_rules_file = os.path.isfile(f'{current_path}/{ALGOLIA_INDEX_NAME}_rules.json') 47 | is_synonyms_file = os.path.isfile(f'{current_path}/{ALGOLIA_INDEX_NAME}_synonyms.json') 48 | 49 | if not is_index_file: 50 | print('No index file available. Terminating script.') 51 | exit() 52 | 53 | # Load the json files so that the data can be restored 54 | with open(f'{current_path}/{ALGOLIA_INDEX_NAME}_index.json', 'r', encoding='utf-16') as f: 55 | index_data = json.load(f) 56 | 57 | if is_settings_file: 58 | with open(f'{current_path}/{ALGOLIA_INDEX_NAME}_settings.json', 'r', encoding='utf-16') as f: 59 | settings_data = json.load(f) 60 | 61 | if is_rules_file: 62 | with open(f'{current_path}/{ALGOLIA_INDEX_NAME}_rules.json', 'r', encoding='utf-16') as f: 63 | rules_data = json.load(f) 64 | 65 | if is_synonyms_file: 66 | with open(f'{current_path}/{ALGOLIA_INDEX_NAME}_synonyms.json', 'r', encoding='utf-16') as f: 67 | synonyms_data = json.load(f) 68 | 69 | # Check the status of the current index. 70 | try: 71 | existing_records = list(index.browse_objects( 72 | {"attributesToRetrieve": ["objectId"]} 73 | )) 74 | except Exception as e: 75 | print(f'Error querying existing index {e}. Exiting') 76 | exit() 77 | 78 | # Confirm with the user that they're going to overwrite an existing index 79 | confirmation = '' 80 | 81 | while confirmation.lower() not in ['y', 'n', 'yes', 'no']: 82 | confirmation = input(f'\ 83 | WARNING: Continuing will overwrite {str(len(existing_records))} records \ 84 | in existing index "{ALGOLIA_INDEX_NAME}" with {str(len(index_data))} records from local index. \ 85 | Do you want to continue (Y/N): ' 86 | ) 87 | 88 | if confirmation.lower() in ['n', 'no']: 89 | print('Exiting process.') 90 | exit() 91 | 92 | # Restore the index and associated data to the application. 93 | try: 94 | print('Restoring index...') 95 | index.replace_all_objects(index_data, { 96 | 'safe': True 97 | }) 98 | print('Index restored.') 99 | 100 | if is_settings_file: 101 | print('Restoring settings...') 102 | index.set_settings(settings_data) 103 | print('Settings restored...') 104 | 105 | if is_rules_file: 106 | print('Restoring rules...') 107 | index.replace_all_rules(rules_data) 108 | print('Rules restored...') 109 | 110 | if is_synonyms_file: 111 | print('Restoring synonyms...') 112 | index.replace_all_synonyms(synonyms_data) 113 | print('Synonyms restored...') 114 | except Exception as e: 115 | print(f'Error restoring index data: {e}') 116 | exit() -------------------------------------------------------------------------------- /python/set_settings.py: -------------------------------------------------------------------------------- 1 | from algoliasearch.search_client import SearchClient 2 | 3 | # Import the environment variables from the .env file 4 | from dotenv import load_dotenv 5 | import os 6 | 7 | load_dotenv() 8 | 9 | # Algolia client credentials 10 | ALGOLIA_APP_ID = os.getenv('ALGOLIA_APP_ID') 11 | ALGOLIA_API_KEY = os.getenv('ALGOLIA_API_KEY') 12 | ALGOLIA_INDEX_NAME = os.getenv('ALGOLIA_INDEX_NAME') 13 | 14 | # Initialize the client 15 | # https://www.algolia.com/doc/api-client/getting-started/initialize/python/?client=python 16 | client = SearchClient.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 17 | 18 | # Initialize the index 19 | # https://www.algolia.com/doc/api-client/getting-started/initialize/python/?client=python 20 | index = client.init_index(ALGOLIA_INDEX_NAME) 21 | 22 | # Set your index settings 23 | # attributesForFaceting 24 | # https://www.algolia.com/doc/api-reference/api-parameters/attributesForFaceting/ 25 | # filterOnly : the attribute will be filterable only and not facetable. 26 | # searchable : the attribute will be be searchable. 27 | # customRanking : You can decide whether the order should be descending or ascending. 28 | # https://www.algolia.com/doc/guides/managing-results/must-do/custom-ranking/ 29 | index.set_settings({ 30 | "searchableAttributes": ["name", "address"], 31 | 'attributesForFaceting': ["name", "filterOnly(address)","searchable(followers)"], 32 | "customRanking": ["desc(followers)"] 33 | }) 34 | 35 | # Get index configuration 36 | print(index.get_settings()) 37 | -------------------------------------------------------------------------------- /python/simple.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | 3 | # Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/python/?client=python 4 | from algoliasearch.search_client import SearchClient 5 | from dotenv import load_dotenv, find_dotenv 6 | 7 | load_dotenv(find_dotenv()) 8 | 9 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 10 | # and choose a name for your index. Add these environment variables to a `.env` file: 11 | ALGOLIA_APP_ID = getenv('ALGOLIA_APP_ID') 12 | ALGOLIA_API_KEY = getenv('ALGOLIA_API_KEY') 13 | ALGOLIA_INDEX_NAME = getenv('ALGOLIA_INDEX_NAME') 14 | 15 | # Start the API client 16 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 17 | client = SearchClient.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 18 | 19 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 20 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 21 | index = client.init_index(ALGOLIA_INDEX_NAME) 22 | 23 | # Add new objects to the index 24 | # https://www.algolia.com/doc/api-reference/api-methods/add-objects/ 25 | new_object = {'objectID': 1, 'name': 'Foo'} 26 | res = index.save_objects([new_object]) 27 | 28 | # Wait for the indexing task to complete 29 | # https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 30 | res.wait() 31 | 32 | # Search the index for "Fo" 33 | # https://www.algolia.com/doc/api-reference/api-methods/search/ 34 | objects = index.search('Fo') 35 | print(objects) 36 | -------------------------------------------------------------------------------- /ruby/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] Ruby version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.0, 2, 2.7, 2.6, 3-bullseye, 3.0-bullseye, 2-bullseye, 2.7-bullseye, 2.6-bullseye, 3-buster, 3.0-buster, 2-buster, 2.7-buster, 2.6-buster 2 | ARG VARIANT=2-bullseye 3 | FROM mcr.microsoft.com/vscode/devcontainers/ruby:${VARIANT} 4 | 5 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 6 | ARG NODE_VERSION="none" 7 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 8 | 9 | # [Optional] Uncomment this section to install additional OS packages. 10 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 11 | # && apt-get -y install --no-install-recommends 12 | 13 | # [Optional] Uncomment this line to install additional gems. 14 | # RUN gem install 15 | 16 | # [Optional] Uncomment this line to install global node packages. 17 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /ruby/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Ruby", 3 | "runArgs": ["--init"], 4 | "build": { 5 | "dockerfile": "Dockerfile", 6 | "args": { 7 | // Update 'VARIANT' to pick a Ruby version: 3, 3.0, 2, 2.7, 2.6 8 | // Append -bullseye or -buster to pin to an OS version. 9 | // Use -bullseye variants on local on arm64/Apple Silicon. 10 | "VARIANT": "3-bullseye", 11 | // Options 12 | "NODE_VERSION": "lts/*" 13 | } 14 | }, 15 | 16 | // Set *default* container specific settings.json values on container create. 17 | "settings": {}, 18 | 19 | // Add the IDs of extensions you want installed when the container is created. 20 | "extensions": [ 21 | "rebornix.Ruby" 22 | ], 23 | 24 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 25 | // "forwardPorts": [], 26 | 27 | // Use 'postCreateCommand' to run commands after the container is created. 28 | // "postCreateCommand": "ruby --version", 29 | 30 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 31 | "remoteUser": "vscode", 32 | "postStartCommand": "bundle install", 33 | } -------------------------------------------------------------------------------- /ruby/.env.example: -------------------------------------------------------------------------------- 1 | ALGOLIA_APP_ID= 2 | ALGOLIA_API_KEY= 3 | ALGOLIA_INDEX_NAME= 4 | -------------------------------------------------------------------------------- /ruby/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem 'dotenv' 4 | gem 'algolia' 5 | -------------------------------------------------------------------------------- /ruby/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | algolia (2.3.4) 5 | faraday (>= 0.15, < 3) 6 | faraday-net_http_persistent (>= 0.15, < 3) 7 | multi_json (~> 1.0) 8 | net-http-persistent 9 | connection_pool (2.4.1) 10 | dotenv (3.1.0) 11 | faraday (2.9.0) 12 | faraday-net_http (>= 2.0, < 3.2) 13 | faraday-net_http (3.1.0) 14 | net-http 15 | faraday-net_http_persistent (2.1.0) 16 | faraday (~> 2.5) 17 | net-http-persistent (~> 4.0) 18 | multi_json (1.15.0) 19 | net-http (0.4.1) 20 | uri 21 | net-http-persistent (4.0.2) 22 | connection_pool (~> 2.2) 23 | uri (0.13.0) 24 | 25 | PLATFORMS 26 | arm64-darwin-23 27 | x86_64-linux 28 | 29 | DEPENDENCIES 30 | algolia 31 | dotenv 32 | 33 | BUNDLED WITH 34 | 2.2.22 35 | -------------------------------------------------------------------------------- /ruby/README.md: -------------------------------------------------------------------------------- 1 | # API Clients Quickstarts: Ruby 2 | 3 | This quickstart demonstrates various usages of the the [Algolia Ruby API Client](https://www.algolia.com/doc/api-client/getting-started/install/python/?client=ruby). 4 | 5 | ## Setting up the quickstart 6 | 7 | ### Prerequisites 8 | 9 | - An Algolia account. If you don't have one already, [create an account for free](https://www.algolia.com/users/sign_up). 10 | - A Ruby ^2.2 local environment, or [Docker](https://www.docker.com/get-started). 11 | 12 |
13 | Using VSCode 14 | 15 | By using VScode and having the [Visual Studio Code Remote - Containers](https://code.visualstudio.com/docs/remote/containers) extension installed, you can run any of the quickstarts by using the command [Remote-Containers: Open Folder in Container](https://code.visualstudio.com/docs/remote/containers#_quick-start-open-an-existing-folder-in-a-container) command. 16 | 17 | Each of the quickstart contains a [.devcontainer.json](./.devcontainer/devcontainer.json), along with a [Dockerfile](./.devcontainer/Dockerfile). 18 |
19 | 20 | 1. Create an Algolia Application and an [Algolia Index](https://www.algolia.com/doc/guides/getting-started/quick-start/tutorials/getting-started-with-the-dashboard/#indices) 21 | 2. Copy the file [.env.example](.env.example) and rename it to `.env` 22 | 3. Set the environment variables `ALGOLIA_APP_ID`, `ALGOLIA_API_KEY` and `ALGOLIA_INDEX_NAME` in the `.env` file. You can obtain those from the [Algolia Dashboard](https://www.algolia.com/api-keys/). The `ALGOLIA_API_KEY` should be the "Admin API Key" (necessary for indexing). 23 | 24 | ## How to use 25 | 26 | Once setup, you can run each of the script in this folder using the PHP command line. 27 | Example: to execute the `simple.rb` script: 28 | 29 | ```bash 30 | ruby simple.rb 31 | ``` 32 | 33 | ## Available quickstarts 34 | 35 | | File | Description | 36 | | ------------- | ------------- | 37 | | [simple.rb](./simple.rb) | Index a single object and run a search query | 38 | | [indexing.rb](./indexing.rb) | Showcase of the main indexing methods | 39 | -------------------------------------------------------------------------------- /ruby/backup_index.rb: -------------------------------------------------------------------------------- 1 | # Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/ruby/?client=ruby 2 | require 'algolia' 3 | require 'dotenv/load' 4 | require 'json' 5 | 6 | # Algolia client credentials 7 | ALGOLIA_APP_ID = ENV['ALGOLIA_APP_ID'] 8 | ALGOLIA_API_KEY = ENV['ALGOLIA_API_KEY'] 9 | ALGOLIA_INDEX_NAME = ENV['ALGOLIA_INDEX_NAME'] 10 | 11 | # Initialize the client and the index 12 | # https://www.algolia.com/doc/api-client/getting-started/initialize/ruby/?client=ruby#initialize-the-search-client 13 | client = Algolia::Search::Client.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 14 | index = client.init_index(ALGOLIA_INDEX_NAME) 15 | 16 | # Retrieve records 17 | puts 'Retrieving records...' 18 | records = index.browse({})['hits'] 19 | puts "#{records.length} records retrieved" -------------------------------------------------------------------------------- /ruby/export_and_add_rule_to_index.rb: -------------------------------------------------------------------------------- 1 | require 'algolia' 2 | require 'dotenv/load' 3 | require 'json' 4 | 5 | # Algolia client credentials 6 | ALGOLIA_APP_ID = ENV['ALGOLIA_APP_ID'] 7 | ALGOLIA_API_KEY = ENV['ALGOLIA_API_KEY'] 8 | ALGOLIA_INDEX_NAME = ENV['ALGOLIA_INDEX_NAME'] 9 | 10 | # Initialize the client and the index 11 | # https://www.algolia.com/doc/api-client/getting-started/initialize/ruby/?client=ruby#initialize-the-search-client 12 | client = Algolia::Search::Client.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 13 | index = client.init_index(ALGOLIA_INDEX_NAME) 14 | 15 | # Create a rule 16 | # https://www.algolia.com/doc/api-reference/api-methods/save-rule/?client=ruby 17 | puts "Creating a rule ..." 18 | rule = { 19 | objectID: 'a-rule-id', 20 | conditions: [{ 21 | pattern: 'Jimmie', 22 | anchoring: 'is' 23 | }], 24 | consequence: { 25 | params: { 26 | filters: "zip_code = 12345" 27 | } 28 | } 29 | } 30 | 31 | # Optionally, to disable the rule 32 | rule['enabled'] = false 33 | 34 | # Optionally, to add validity time ranges 35 | rule['validity'] = [ 36 | { 37 | from: Time.now.to_i, 38 | until: (DateTime.now + 10).to_time.to_i, 39 | } 40 | ] 41 | 42 | # Save the Rule. 43 | index.save_rule(rule) 44 | # Save the Rule and wait the end of indexing. 45 | index.save_rule!(rule) 46 | # Save the Rule, and forward it to all replicas of the index. 47 | response = index.save_rule(rule, { forwardToReplicas: true }) 48 | 49 | 50 | # Browse rules 51 | # https://www.algolia.com/doc/api-reference/api-methods/export-rules/ 52 | res = index.browse_rules() 53 | 54 | # Store rules into an array 55 | rules = res.map {|rule| rule} 56 | 57 | if rules.empty? 58 | puts "No rules are configured for your index yet." 59 | else 60 | # Create the json file with all rules 61 | path = "#{ALGOLIA_INDEX_NAME}_rules.json" 62 | File.open(path, 'wb') do |file| 63 | file.write(JSON.generate(rules)) 64 | end 65 | puts "Rules export completed" 66 | end 67 | 68 | -------------------------------------------------------------------------------- /ruby/generate_key.rb: -------------------------------------------------------------------------------- 1 | require 'dotenv/load' 2 | require 'algolia' 3 | 4 | # Algolia client credentials 5 | ALGOLIA_APP_ID = ENV['ALGOLIA_APP_ID'] 6 | ALGOLIA_API_KEY = ENV['ALGOLIA_API_KEY'] 7 | ALGOLIA_INDEX_NAME = ENV['ALGOLIA_INDEX_NAME'] 8 | 9 | # Initialize the client and the index 10 | # https://www.algolia.com/doc/api-client/getting-started/initialize/ruby/?client=ruby#initialize-the-search-client 11 | client = Algolia::Search::Client.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 12 | index = client.init_index(ALGOLIA_INDEX_NAME) 13 | 14 | # Set permissions for API key 15 | # https://www.algolia.com/doc/api-reference/api-methods/add-api-key/?client=ruby#method-param-acl 16 | acl = ['search'] 17 | 18 | # Set the rate limited parameters for API key 19 | # https://www.algolia.com/doc/api-reference/api-methods/add-api-key/#method-param-maxqueriesperipperhour 20 | 21 | opts = { 22 | description: "Restricted search-only API key limited to 100 API calls per hour", 23 | # Rate-limit to 100 requests per hour per IP address 24 | maxQueriesPerIPPerHour: 100 25 | } 26 | 27 | # Create a new restricted search-only API key 28 | puts "Creating new restricted search-only API key ..." 29 | 30 | res = client.add_api_key(acl, opts) 31 | 32 | # Print the new generated search api key 33 | new_search_api_key = res.raw_response[:key] 34 | puts "Your new Search only Rate Limited API Key is: #{new_search_api_key}" -------------------------------------------------------------------------------- /ruby/index_settings.rb: -------------------------------------------------------------------------------- 1 | # Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/ruby/?client=ruby 2 | require 'dotenv/load' 3 | require 'algolia' 4 | 5 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 6 | # and choose a name for your index. Add these environment variables to a `.env` file: 7 | ALGOLIA_APP_ID = ENV['ALGOLIA_APP_ID'] 8 | ALGOLIA_API_KEY = ENV['ALGOLIA_API_KEY'] 9 | ALGOLIA_INDEX_NAME = ENV['ALGOLIA_INDEX_NAME'] 10 | 11 | # Start the API client 12 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 13 | client = Algolia::Search::Client.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 14 | 15 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 16 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 17 | index = client.init_index(ALGOLIA_INDEX_NAME) 18 | 19 | 20 | # Changing index settings 21 | # https://www.algolia.com/doc/api-reference/api-methods/set-settings/ 22 | index.set_settings({ 23 | # https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/ 24 | typoTolerance: true, 25 | # https://www.algolia.com/doc/api-reference/api-parameters/queryLanguages/ 26 | queryLanguages: ['es'], 27 | # https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/ 28 | ignorePlurals: true 29 | }) 30 | 31 | 32 | # Wait for the indexing task to complete 33 | # https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 34 | res.wait() 35 | 36 | # Search the index for "Fo" 37 | # https://www.algolia.com/doc/api-reference/api-methods/search/ 38 | objects = index.search('Fo') 39 | puts objects 40 | -------------------------------------------------------------------------------- /ruby/indexing.rb: -------------------------------------------------------------------------------- 1 | require 'dotenv/load' 2 | require 'algolia' 3 | 4 | # Algolia client credentials 5 | ALGOLIA_APP_ID = ENV['ALGOLIA_APP_ID'] 6 | ALGOLIA_API_KEY = ENV['ALGOLIA_API_KEY'] 7 | ALGOLIA_INDEX_NAME = ENV['ALGOLIA_INDEX_NAME'] 8 | 9 | # Initialize the client 10 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 11 | client = Algolia::Search::Client.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 12 | 13 | # Initialize an index 14 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 15 | index = client.init_index(ALGOLIA_INDEX_NAME) 16 | 17 | # Define some objects to add to our index 18 | # https://www.algolia.com/doc/api-client/methods/indexing/#object-and-record 19 | contacts = [ 20 | { 21 | name: 'Foo', 22 | objectID: '1' 23 | }, 24 | { 25 | name: 'Bar', 26 | objectID: '2' 27 | } 28 | ] 29 | 30 | # We don't have any objects (yet) in our index 31 | res = index.search('') 32 | puts 'Current objects: ', res[:hits], "\n" 33 | 34 | # Save Objects: Add mutliple new objects to an index. 35 | # https://www.algolia.com/doc/api-reference/api-methods/add-objects/?client=ruby 36 | puts 'Save Objects - Adding multiple objects: ', contacts 37 | index.save_objects!(contacts) 38 | 39 | res = index.search('') 40 | puts 'Current objects: ', res[:hits], "\n" 41 | 42 | # Save Objects: Replace an existing object with an updated set of attributes. 43 | # https://www.algolia.com/doc/api-reference/api-methods/save-objects/?client=ruby 44 | puts 'Save Objects - Replacing objects’s attributes on:', contacts[0] 45 | new_contact = { 46 | name: 'FooBar', 47 | objectID: '1' 48 | } 49 | index.save_object!(new_contact) 50 | 51 | res = index.search('') 52 | puts 'Current objects: ', res[:hits], "\n" 53 | 54 | # Partial Update Objects: Update one or more attributes of an existing object. 55 | # https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/?client=ruby 56 | puts 'Save Objects - Updating object’s attributes on:', contacts[0] 57 | new_contact = { 58 | email: 'foo@bar.com', # New attribute 59 | objectID: '1' 60 | } 61 | index.partial_update_object!(new_contact) 62 | 63 | res = index.search('') 64 | puts 'Current objects: ', res[:hits], "\n" 65 | 66 | # Delete Objects: Remove objects from an index using their objectID. 67 | # https://www.algolia.com/doc/api-reference/api-methods/delete-objects/?client=ruby 68 | objectID_to_delete = contacts[0][:objectID] 69 | puts 'Delete Objects - Deleting object with objectID: "%s"' % objectID_to_delete 70 | index.delete_object!(objectID_to_delete) 71 | 72 | res = index.search('') 73 | puts 'Current objects: ', res[:hits], "\n" 74 | 75 | # Replace All Objects: Clears all objects from your index and replaces them with a new set of objects. 76 | # https://www.algolia.com/doc/api-reference/api-methods/replace-all-objects/?client=ruby 77 | new_contacts = [ 78 | { 79 | name: 'NewFoo', 80 | objectID: '3' 81 | }, 82 | { 83 | name: 'NewBar', 84 | objectID: '4' 85 | } 86 | ] 87 | puts 'Replace All Objects - Clears all objects and replaces them with:', new_contacts 88 | res = index.replace_all_objects!(new_contacts) 89 | 90 | res = index.search('') 91 | puts 'Current objects: ', res[:hits], "\n" 92 | 93 | # Delete By: Remove all objects matching a filter (including geo filters). 94 | # https://www.algolia.com/doc/api-reference/api-methods/delete-by/?client=ruby 95 | puts 'Delete By - Remove all objects matching "name:NewBar"' 96 | 97 | # Firstly, have an attribute to filter on 98 | # https://www.algolia.com/doc/api-client/methods/settings/?client=ruby 99 | index.set_settings({ 100 | attributesForFaceting: ['name'] 101 | }).wait() 102 | 103 | index.delete_by({ 104 | facetFilters: ['name:NewBar'] # https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ 105 | }).wait() 106 | 107 | res = index.search('') 108 | puts 'Current objects: ', res[:hits], "\n" 109 | 110 | # Get Objects: Get one or more objects using their objectIDs. 111 | # https://www.algolia.com/doc/api-reference/api-methods/get-objects/?client=ruby 112 | object_id = new_contacts[0][:objectID] 113 | puts 'Get Objects - Getting object with objectID "%s"' % object_id 114 | 115 | res = index.get_object(object_id) 116 | puts 'Results: ', res, "\n" 117 | 118 | # Custom Batch: Perform several indexing operations in one API call. 119 | # https://www.algolia.com/doc/api-reference/api-methods/batch/?client=ruby 120 | operations = [ 121 | { 122 | action: 'addObject', 123 | indexName: ALGOLIA_INDEX_NAME, 124 | body: { 125 | name: 'BatchedBar', 126 | } 127 | }, 128 | { 129 | action: 'updateObject', 130 | indexName: ALGOLIA_INDEX_NAME, 131 | body: { 132 | objectID: object_id, 133 | name: 'NewBatchedBar', 134 | } 135 | } 136 | ] 137 | puts 'Custom Batch - Batching %d operations' % operations.length 138 | res = client.multiple_batch!(operations) 139 | 140 | res = index.search('') 141 | puts 'Current objects: ', res[:hits], "\n" 142 | 143 | 144 | # Clear Objects: Clear the records of an index without affecting its settings. 145 | # https://www.algolia.com/doc/api-reference/api-methods/clear-objects/?client=ruby 146 | puts 'Clear Objects: Clear the records of an index without affecting its settings.' 147 | index.clear_objects!() 148 | 149 | # We don't have any objects in our index 150 | res = index.search('') 151 | puts 'Current objects: ', res[:hits] 152 | -------------------------------------------------------------------------------- /ruby/rules.rb: -------------------------------------------------------------------------------- 1 | # Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/ruby/?client=ruby 2 | require 'dotenv/load' 3 | require 'algolia' 4 | # require 'date' 5 | 6 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 7 | # and choose a name for your index. Add these environment variables to a `.env` file: 8 | ALGOLIA_APP_ID = ENV['ALGOLIA_APP_ID'] 9 | ALGOLIA_API_KEY = ENV['ALGOLIA_API_KEY'] 10 | ALGOLIA_INDEX_NAME = ENV['ALGOLIA_INDEX_NAME'] 11 | 12 | # Start the API client 13 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 14 | client = Algolia::Search::Client.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 15 | 16 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 17 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 18 | index = client.init_index(ALGOLIA_INDEX_NAME) 19 | 20 | # Exporting the rules 21 | # https://www.algolia.com/doc/api-reference/api-methods/export-rules/#examples 22 | print "Original rules:\n" 23 | all_rules = index.browse_rules() 24 | all_rules.each { |rule| puts rule } 25 | print "\n" 26 | 27 | # Adding a new rule 28 | # https://www.algolia.com/doc/api-reference/api-methods/save-rule/?client=php 29 | rule_id = 'a-rule-id' 30 | print "Adding new rule: #{rule_id}\n" 31 | 32 | rule = { 33 | objectID: rule_id, 34 | conditions: [{ 35 | pattern: 'dress', 36 | anchoring: 'contains', 37 | # Uncomment line 38 if the pattern should match plurals, synonyms, and typos. 38 | # alternatives: true 39 | }], 40 | consequence: { 41 | params: { 42 | filters: 'subCategory:Dress' 43 | } 44 | } 45 | } 46 | 47 | # Uncomment line 48 to turn the rule off 48 | # rule['enabled'] = false 49 | 50 | # Uncomment lines 51 - 56 to add valid time ranges (also uncomment `require 'date'` on line 4) 51 | # rule['validity'] = [ 52 | # { 53 | # from: Time.now.to_i, 54 | # until: (DateTime.now + 10).to_time.to_i, 55 | # } 56 | # ] 57 | 58 | # Save the Rule. 59 | index.save_rule(rule) 60 | 61 | 62 | # Save the Rule, and forward it to all replicas of the index. 63 | # index.save_rule(rule, { forwardToReplicas: true }) 64 | 65 | print "#{rule_id} added successfully\n" 66 | print "\n" 67 | 68 | # Exporting the modified rules 69 | # https://www.algolia.com/doc/api-reference/api-methods/export-rules/ 70 | print "Modified rules:\n" 71 | all_modified_rules = index.browse_rules() 72 | all_modified_rules.each { |rule| puts rule } 73 | print "\n" -------------------------------------------------------------------------------- /ruby/simple.rb: -------------------------------------------------------------------------------- 1 | # Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/ruby/?client=ruby 2 | require 'dotenv/load' 3 | require 'algolia' 4 | 5 | # Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys 6 | # and choose a name for your index. Add these environment variables to a `.env` file: 7 | ALGOLIA_APP_ID = ENV['ALGOLIA_APP_ID'] 8 | ALGOLIA_API_KEY = ENV['ALGOLIA_API_KEY'] 9 | ALGOLIA_INDEX_NAME = ENV['ALGOLIA_INDEX_NAME'] 10 | 11 | # Start the API client 12 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ 13 | client = Algolia::Search::Client.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY) 14 | 15 | # Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists) 16 | # https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index 17 | index = client.init_index(ALGOLIA_INDEX_NAME) 18 | 19 | # Add new objects to the index 20 | # https://www.algolia.com/doc/api-reference/api-methods/add-objects/ 21 | new_object = {objectID: 1, name: 'Foo'} 22 | res = index.save_objects([new_object]) 23 | 24 | # Wait for the indexing task to complete 25 | # https://www.algolia.com/doc/api-reference/api-methods/wait-task/ 26 | res.wait() 27 | 28 | # Search the index for "Fo" 29 | # https://www.algolia.com/doc/api-reference/api-methods/search/ 30 | objects = index.search('Fo') 31 | puts objects 32 | -------------------------------------------------------------------------------- /yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | --------------------------------------------------------------------------------