Giter Site home page Giter Site logo

typesense / typesense-swift Goto Github PK

View Code? Open in Web Editor NEW
36.0 9.0 15.0 9.87 MB

Swift Client for Typesense โšก๏ธ๐Ÿ”Ž

Home Page: https://typesense.org/docs/

License: Apache License 2.0

Swift 98.92% Shell 1.08%
typesense search swift ios

typesense-swift's Introduction

Typesense Swift

A great new way to implement your searches on iOS using Typesense โšก๏ธ๐Ÿ”โœจ Typesense Swift is a high level wrapper that helps you easily implement searching using Typesense.

Installation

Add Typesense Swift Swift Package to your project. You can refer Apple's Documentation to add Typesense Swift as a dependency to your iOS Project. You can also import Typesense into your own Swift Package by adding this line to dependencies array of Package.swift:

...
dependencies: [
           .package(url: "https://github.com/typesense/typesense-swift", .upToNextMajor(from: "0.2.0"),
],
...

Usage

Setting up the client

Import Typesense onto your Swift Project:

import Typesense

Declare the Typesense nodes that are available as Node members:

let node1 = Node(host: "localhost", port: "8108", nodeProtocol: "http")
let node2 = Node(host: "super-awesome.search", port: "8080", nodeProtocol: "https") //and so on

Create a configuration and hence a client with the Nodes mentioned:

let myConfig = Configuration(nodes: [node1, node2], apiKey: "coolstuff")

let client = Client(config: myConfig)

You can use Typesense parameters like nearestNode and connectionTimeoutSeconds while creating the configuration. You can also pass in a logger parameter to debug the code like this:

let myConfig = Configuration(nodes: [node1, node2], apiKey: "coolstuff", logger: Logger(debugMode: true))

Indexing documents

You can create a collection by first defining a collection schema:

let myCoolSchema = CollectionSchema(name: "schools", fields: [Field(name: "school_name", type: "string"), Field(name: "num_students", type: "int32"), Field(name: "country", type: "string", facet: true)], defaultSortingField: "num_students")
    
let (data, response) = try await client.collections.create(schema: myCoolSchema)

Define the structure of your document as per your collection, and index it by inserting/upserting it to the collection:

struct School: Codable {
    var id: String
    var school_name: String
    var num_students: Int
    var country: String
}

let document = School(id: "7", school_name: "Hogwarts", num_students: 600, country: "United Kingdom")
let documentData = try JSONEncoder().encode(document)
let (data, response) = try await client.collection(name: "schools").documents().create(document: documentData)
//or 
let (data, response) = try await client.collection(name: "schools").documents().upsert(document: documentData)

You can perform CRUD actions to Collections and Documents that belong to a certain collection. You can also use .importBatch() on the documents() method to import and index a batch of documents (in .jsonl format).

Searching

Define your search parameters clearly and then perform the search operation by mentioning your Document Type:

let searchParameters = SearchParameters(q: "hog", queryBy: "school_name", filterBy: "num_students:>500", sortBy: "num_students:desc")

let (data, response) = try await client.collection(name: "schools").documents().search(searchParameters, for: School.self)

This returns a SearchResult object as the data, which can be further parsed as desired.

Contributing

Issues and pull requests are welcome on GitHub at Typesense Swift. Do note that the Models used in the Swift client are generated by Swagger-Codegen and are automated to be modified in order to prevent major errors. So please do use the shell script that is provided in the repo to generate the models:

sh get-models.sh

The generated Models (inside the Models directory) are to be used inside the Models directory of the source code as well. Models need to be generated as and when the Typesense-Api-Spec is updated.

TODO: Features

  • Curation API
  • Dealing with Dirty Data
  • Scoped Search Key

typesense-swift's People

Contributors

jasonbosco avatar programveins avatar willtempleton 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typesense-swift's Issues

Non async version

Description

My app supports back to iOS 11 so I am not using async-await yet. Is it possible to use this package without async await?

How to fetch hits on the second page?

Description

I use the following swift code to fetch hits from "companies" collection:

let searchParameters = SearchParameters(q: "\(searchText)", queryBy: "description", page: 3, perPage: 3)
let (searchData, _) = try await client.collection(name: "companies").documents().search(searchParameters, for: companyData.self)

When I print "searchData" out, it shows it can fetch data (3 pages with 3 hits on each page). However, in "searchData" there are only 3 hits from the first page. No more hits shown in "searchData". I use the following code to get access to hits on the first page:

for index in 0...2 {
searchData?.hits?[index].document?
}

My question is how to get access to hits on other pages? e.g., 3 hits on the second or third page?

Unable to use `facetBy`

Description

When facetBy is specified, results cannot be decoded. I believe this is because SearchResult.facetCounts is defined as [Int]?, but the actual value of that field is an array of documents that look like this:

facet_counts": [
        {
            "counts": [
                {
                    "count": 4,
                    "highlighted": "Value A",
                    "value": "Value A"
                },
                ...
                {
                    "count": 1,
                    "highlighted": "Value B",
                    "value": "Value B"
                }
            ],
            "field_name": "some_field",
            "stats": {
                "total_values": 7
            }
        }
]

Steps to reproduce

Execute a search with one or more fields specified in facetBy.

Expected Behavior

A usable SearchResult object is returned.

Actual Behavior

A decoding exception is thrown.

Metadata

Typesense Version: 0.24.1

OS: iOS 17.0.3

Can't install the package through Xcode (12.5)

I'm trying to install Typesense-Swift through Xcode's package manager, but keep hitting this error:

"package at 'https://github.com/typesense/typesense-swift.git' @ .... is using Swift tools version 5.5.0 but the installed version is 5.4.0 in https://github.com/typesense/typesense-swift.git"

Steps to reproduce

Try downloading through Xcode Package Manager (File > Swift Packages > Add Package Dependency > [Choose Project] > [Search for package] > [Install it]

Expected Behavior

To download the package

Actual Behavior

Error:
"package at 'https://github.com/typesense/typesense-swift.git' @ .... is using Swift tools version 5.5.0 but the installed version is 5.4.0 in https://github.com/typesense/typesense-swift.git"

My app's minimum target is iOS 12.1 and I'm on macOS big sur using Xcode version 12.5

StringQuantum Conversion

How do I actually convert the StringQuantum to a [String] and access each word in there?
For example I have:
hits![indexPath.row].highlights![0].matchedTokens!
Yet I am stuck with the StringQuantum data type and have no idea how to convert it to an array of Strings.

Bug: Synchronous for loop

Make for loop asynchronous

  • For loop for numRetries in ApiCall is executed synchronously, so only after the (numRetries + 1)th iteration, the first response is fetched.
  • Check for node's health must be initiated before the next iteration - for loop must run asynchronously.
  • Check Node health at each iteration and loop depending on that

Incompatible with iOS 13-14

The minimum deployment target is set to iOS 13 but the client is not compatible with iOS 13-14 because, URLSession.data(for:delegate:) is available only on iOS 15+

This needs a workaround to bring back modern concurrency to iOS 13-14 as well.

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.