GithubHelp home page GithubHelp logo

algolia / algoliasearch-client-go Goto Github PK

View Code? Open in Web Editor NEW
201.0 85.0 62.0 57.56 MB

⚡️ A fully-featured and blazing-fast Go API client to interact with Algolia.

Home Page: https://www.algolia.com/doc/api-client/go/getting-started/

License: MIT License

Makefile 0.09% Go 99.57% Shell 0.30% Dockerfile 0.03%
go algolia-search algolia api-client search

algoliasearch-client-go's Introduction

Algolia for Go

The perfect starting point to integrate Algolia within your Go project

CircleCI Github Releases GoDoc Go Report Card License Supported version

DocumentationCommunity ForumStack OverflowReport a bugFAQSupport

✨ Features

  • Support Go 1.11 and above
  • Typed requests and responses
  • First-class support for user-defined structures
  • Injectable HTTP client

Migration note from v2.x to v3.x

In June 2019, we released v3 of our Go client. If you are using version 2.x of the client, read the migration guide to version 3.x. Version 2.x will no longer be under active development.

💡 Getting Started

First, add the Algolia Go API Client as a new module to your Go project:

# First line is optional if your project is already defined as a Go module
go mod init <YOUR_PROJECT_NAME>
go get github.com/algolia/algoliasearch-client-go/[email protected]

Then, create objects on your index:

package main

import "github.com/algolia/algoliasearch-client-go/v3/algolia/search"

type Contact struct {
	ObjectID string `json:"objectID"`
	Name     string `json:"name"`
}

func main() {
	client := search.NewClient("YourApplicationID", "YourAPIKey")
	index := client.InitIndex("your_index_name")

	res, err := index.SaveObjects([]Contact{
		{ObjectID: "1", Name: "Foo"},
	})
}

Finally, you may begin searching a object using the Search method:

package main

import (
	"fmt"
	"os"

	"github.com/algolia/algoliasearch-client-go/v3/algolia/search"
)

type Contact struct {
	ObjectID string `json:"objectID"`
	Name     string `json:"name"`
}

func main() {
	client := search.NewClient("YourApplicationID", "YourAPIKey")
	index := client.InitIndex("your_index_name")

	res, err := index.Search("Foo")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	var contacts []Contact

	err = res.UnmarshalHits(&contacts)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(contacts)
}

For full documentation, visit the Algolia Go API Client.

❓ Troubleshooting

Encountering an issue? Before reaching out to support, we recommend heading to our FAQ where you will find answers for the most common issues and gotchas with the client.

🐳 Use the Dockerfile

If you wish to contribute to the repository but would like to avoid installing the dependencies locally, we provided you with a Docker image. Please check our dedicated guide to learn more.

📄 License

Algolia Go API Client is an open-sourced software licensed under the MIT license.

algoliasearch-client-go's People

Contributors

algoliareadmebot avatar andyhaskell avatar argon avatar aseure avatar cdhawke avatar clemfromspace avatar csquared avatar dkurzaj avatar elpicador avatar ferhatelmas avatar fluf22 avatar jojva avatar julienbourdeau avatar k-yomo avatar kujenga avatar l4u avatar leoercolanelli avatar mehmetaligok avatar nagriar avatar oinume avatar pixelastic avatar poweroftrue avatar rayrutjes avatar redox avatar samouss avatar sarahdayan avatar sfriquet avatar shortcuts avatar speedblue avatar vladislavfitz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

algoliasearch-client-go's Issues

Check returned `Key` fields

Check if the following fields are returned under some conditions:

  • Description string json:"description,omitempty"
  • MaxHitsPerQuery int json:"maxHitsPerQuery,omitempty"
  • MaxQueriesPerIPPerHour int json:"maxQueriesPerIPPerHour,omitempty"
  • QueryParamaters string json:"queryParameters,omitempty"

Error on the DeleteByQuery method when Distinct > 1

In the case the distinct is enabled on an index (with distinct > 1), a call to the method DeleteByQuery returns the following error:

{
  "message": "invalid distinct value, hitsPerPage * distinct should be <= 1000",
  "status": 400
}

We should probably override distinct=false at query time when the method performs the search call.

Cannot go get

go get
# github.com/algolia/algoliasearch-client-go/algoliasearch
../../algolia/algoliasearch-client-go/algoliasearch/Transport.go:110: t.httpClient.Transport.(*http.Transport).TLSHandshakeTimeout undefined (type *http.Transport has no field or method TLSHandshakeTimeout)
../../algolia/algoliasearch-client-go/algoliasearch/Transport.go:183: t.httpClient.Transport.(*http.Transport).TLSHandshakeTimeout undefined (type *http.Transport has no field or method TLSHandshakeTimeout)

Use of "syscall" in the package itself prevents use within Google App Engine

This PR #95 introduced the use of the syscall package within the client library itself, where it was previously used just in test files.

The Google App Engine sandbox prevents the usage of several libraries within the stdlib, including syscall. Would it be possible to either move the use of syscall back to the tests, or use os.Getenv instead? The checks of the "ok" return parameter from syscall.Getenv could just be replaced with a check for the empty string.

I'm happy to submit a PR doing so!

Shouldn't moveIndex be at the client level?

In all the other clients, it's at the client level.

Ruby

client.move_index('YourIndexName_temp', 'YourIndexName')

Go

client.InitIndex('YourIndexNameTemp').move('YourIndexName')

Cannot "go get"

Worked a few days ago but not today:

go get github.com/algolia/algoliasearch-client-go/algoliasearch
# github.com/algolia/algoliasearch-client-go/algoliasearch
../../algolia/algoliasearch-client-go/algoliasearch/Index.go:194: (*Index).CustomBatch redeclared in this block
    previous declaration at ../../algolia/algoliasearch-client-go/algoliasearch/Client.go:140

Testing flags

When you build a Go project that uses github.com/algolia/algoliasearch-client-go/algoliasearch as well as the flag library from the standard lib, test flags (from the standard testing library) appear in the usage description that shows up when you provide the -h or --help flags:

  -test.bench string
        regular expression to select benchmarks to run
  -test.benchmem
        print memory allocations for benchmarks
  -test.benchtime duration
        approximate run time for each benchmark (default 1s)
  -test.blockprofile string
        write a goroutine blocking profile to the named file after execution
  -test.blockprofilerate int
        if >= 0, calls runtime.SetBlockProfileRate() (default 1)
  -test.count n
        run tests and benchmarks n times (default 1)
  -test.coverprofile string
        write a coverage profile to the named file after execution
  -test.cpu string
        comma-separated list of number of CPUs to use for each test
  -test.cpuprofile string
        write a cpu profile to the named file during execution
  -test.memprofile string
        write a memory profile to the named file after execution
  -test.memprofilerate int
        if >=0, sets runtime.MemProfileRate
  -test.outputdir string
        directory in which to write profiles
  -test.parallel int
        maximum test parallelism (default 4)
  -test.run string
        regular expression to select tests and examples to run
  -test.short
        run smaller test suite to save time
  -test.timeout duration
        if positive, sets an aggregate time limit for all tests
  -test.trace string
        write an execution trace to the named file after execution
  -test.v
        verbose: print additional output

This is due to the existence of the "testing.go" file (https://github.com/algolia/algoliasearch-client-go/blob/master/algoliasearch/testing.go), which does not follow the Go convention for test files, which specifies that all test files should end with _test.go (see: https://golang.org/pkg/testing/#pkg-overview). Because it does not follow the convention, it is not excluded from the build like other test files. This results in the test flags showing up in the usage description (the test flags come from the standard testing library, which is imported in the testing.go file).

Running the following minimal program with the -h or --help flags demonstrates the issue:

package main

import (
    "flag"

    _ "github.com/algolia/algoliasearch-client-go/algoliasearch"
)

func main() {
    flag.Parse()
}

Deleting the testing.go file fixes the issue, as does renaming it to testing_test.go. I suggest renaming it to follow the _test.go convention.

The DeleteByQuery method is wrong

We can't browse the index to take all the maching objectID because if the content of the index changes between two pages, the browse response won't be exact.

So we need to wait the batch of delete to be sure we didn't miss some records and rebrowse the index until the first page of the browse is empty.

Use a POST request for the browse method

Currently we use the GET method for browse but if you have a huge amount of query parameters, you can reach the 414 error (url too long) so it could be nice to use a POST request to avoid it.

Fix `SaveSynonym` signature

Pass objectID is first parameter instead of within the Synonym object, which then should be passed as a second parameter.

Adding a "removeWordsUntilNumberResults" parameter

This would be similar to "removeWordsIfNoResults", but would keep removing words even after receiving results if it did not meet the integer value of this parameter.

Trivial Example:

query: "Red Leather Shoe V2"
removeWordsUntilNumberResults: 3

removeWordsIfNoResults: "Red Leather Shoe" - 1 result, done

removeWordsUntilNumberResults: "Red Leather Shoe" - 1 result, 1 < 3, keep removing words
removeWordsUntilNumberResults: "Red Leather" - 2 result, 2 < 3, keep removing words
removeWordsUntilNumberResults: "Red" - 10 result, 10 > 3, return all 10 results, done

SetSettings gets wrong parameter (algoliasearch.Map)

hey!

The documentation specifies that index.SetSettings gets a Settings object, but the actual method requires a Map object. Also the GetSettings returns a Settings object.

This is kinda confusing for beginners. Is it a documentation bug, or a code bug?

Thanks in advance.

Feature idea: BatchUpdateBody for easier configuration of update BatchOperations

Right now if I want to do an AddUnique on a field I'm updating in a BatchOperation, I'd need to make a field that marshals to JSON as

{
    "_operation": "AddUnique",
    "value": "the item I'm adding"
}

So I had an idea for this type to streamline writing more intricate batch operations

type BatchOpBody map[string]interface{}

type FieldAction struct {
        Op    `json:"_operation"`
        Value `json:"value"`
}

func (b BatchOpBody) SetFieldAction(field, action string) {
        value := b[field]
        b[field] = FieldAction{
                Op: action,
                Value: value,
        }
}

Then someone updating one field, adding an item to a second field, and removing an item from a third field could do something like:

b := algoliasearch.BatchOpBody{
        "fieldImUpdating":      100,
        "fieldImAppendingTo":  "item I'm adding",
        "fieldImRemovingFrom": "item I'm removing", 
}
b.SetFieldAction("fieldImAppendingTo", "AddUnique")
b.SetFieldAction("fieldImRemovingFrom", "Remove")

op := algoliasearch.BatchOperation{
        "Action": "partialUpdateObject",
        "Body": b,
}

What do you think?

Missing optional attributes in the QueryRes

Here is the list of missing fields:

  • offset/length (integer to specify page/hitsPerPage differently)
  • message (string used to return warnings)
  • facets (JObject used for the facet count)
  • facets_stats (JObject same for the stats)
  • exhaustiveFacetsCount (boolean to indicate if the facetsCount and facetsStats are exact)
  • queryAfterRemoval (string to indicate which words are removed with removeWordsIfNoResults)
  • aroundLatLng (string resolved location from the ip)
  • automaticRadius (string radius computed by the engine automatically)
  • index (string to indicate the index name in case of multiqueries)
  • serverUsed (string the hostname of the server)
  • parsedQuery (string the query after the preprocessing of the engine like normalization)
  • timeoutCounts (boolean to indicate if the engine returned an exact nbHits)
  • timeoutHits (boolean to indicate if the query triggered the timeout)

AWS Lambda: socket: too many open files

I am consuming events from a kinesis queue in a lambda function and calling

algoliaIndex := algoliaClient.InitIndex(lambdaEvent.IndexName)
_, algoliaOperationError = algoliaIndex.AddObjects(objectsToSync(lambdaEvent))

After 6,930 successful calls I get the following error:

Cannot perform request [POST] /1/indexes/SyncItem/batch (8OVNLPT6JS-1.algolianet.com): Post https://8OVNLPT6JS-1.algolianet.com/1/indexes/SyncItem/batch: dial tcp: lookup 8OVNLPT6JS-1.algolianet.com on 10.15.0.2:53: dial udp 10.15.0.2:53: socket: too many open files

Is it possible that the Algolia go library doesn't correctly close old connections or am I missing something?

fileSize field in JSON response not in IndexRes

I noticed using a cURL call to the /1/indexes route that there is a field in the JSON response called "fileSize", which contains the index size shown when looking at an index in the dashboard. However, there is no corresponding field in the IndexRes struct in v2 of the Go client. Could this be added?

doc(typo)

The Go documentation has a small typo . Should be InitIndex instead of initIndex (upper case).
index := client.initIndex("YourIndexName")

concurrent usage and persistent connection

Hi all,

I am wondering if it is safe to use a persistent algoliasearch.NewClient throughout my application life, and also use it concurrently for like fetching results. I went through the source code, the httpclient is safe to be used by many goroutines, but I am not sure if other internal structs in this client library is designed with concurrent usage in mind. Any help will be appreciated :)

Array of insideBoundingBox and insidePolygon

To make an UNION of multiple polygons, you can use this syntax: insidePolygon=[[42.01,-124.31, 42,-120.00 ,39.01,-120.00 ,35,-114.63], [46.01,-124.31, 42,-150.00 ,39.01,-120.00 ,35,-114.63]].

Cannot add objects which are not of type map[string]interface{}

Using the following code will result in a panic stating interface conversion: interface {} is main.Media, not map[string]interface {}

package main

import (
    "github.com/algolia/algoliasearch-client-go/algoliasearch"
)

type Media struct{}

func main() {
    client := algoliasearch.NewClient("******", "****************")

    index := client.InitIndex("media")

    m := Media{}

    index.AddObject(m)
}

This doesn't work well with my current system as the database schemas are built using structs and not maps.

However, using the following code will work absolutely fine.

package main

import (
    "github.com/algolia/algoliasearch-client-go/algoliasearch"
)

type Media struct{}

func main() {
    client := algoliasearch.NewClient("******", "****************")

    index := client.InitIndex("media")

    m := Media{}

    index.AddObjects([]interface{}{m})
}

Do you know if you could add support for objects which are not just regular maps?

Add functions waiting for server completion

Most of the time the user wants to wait for the settings to be effective on the server before continuing,
it may be a good idea to add convenience functions that include the "waiting" part.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.