首页 > 解决方案 > 在查询时过滤结果 Algolia Search

问题描述

我正在使用 Kotlin 开发个人 Android 应用程序,我想实现 InstantSearch。我在 Algolia 有以下记录结构:

{
  "creationTime": 1566396861797,
  "description": "It's my second home now...",
  "imagePath": "https://firebasestorage.googleapis.com/.......",
  "memoryId": "-LmoWe8PEqCs0Szv9KKJ",
  "memoryTitle": "Second visit",
  "userId": "vIWJgFpnUSeZJw3wjrJeEAxbNoE2",
  "imageLabels": [
    "Property",
    "Furniture",
    "City",
    "Human settlement",
    "Real estate",
    "Roof",
    "Room",
    "Skyline",
    "Building",
    "Metropolitan area",
    "Sky",
    "Balcony",
    "Apartment"
  ],
  "objectID": "-LmoWe8PEqCs0Szv9KKJ"
}

在我的 InstantSearch 中,我想提供一个搜索,该搜索只显示与userId发送查询的特定用户具有相同值的记录。首先,我将 userId 添加到仪表板中的分面属性中。我不知道如何从这一点继续。我不知道如何在查询时过滤记录。

这是我的视图模型:

class MyViewModel : ViewModel() {
    val client = ClientSearch(ApplicationID("*****"), APIKey("*******"), LogLevel.ALL)
    val index = client.initIndex(IndexName("memory_diary"))
    val searcher = SearcherSingleIndex(index)
    val adapterMemory = MemoryAdapter()
    val dataSourceFactory = SearcherSingleIndexDataSource.Factory(searcher) { hit ->
        Memory(
                hit.json.getPrimitive("userId").content,
                hit.json.getPrimitive("objectID").content,
                hit.json.getPrimitive("memoryTitle").content,
                hit.json.getPrimitive("description").content,
                hit.json.getPrimitive("creationTime").content.toLong(),
                hit.json.getPrimitive("imagePath").content,
                hit.json.getArray("imageLabels").content.map { jsnelm -> jsnelm.content }
        )
    }


    val pagedListConfig = PagedList.Config.Builder().setPageSize(50).build()
    val memories: LiveData<PagedList<Memory>> = LivePagedListBuilder(dataSourceFactory, pagedListConfig).build()

    val searchBox = SearchBoxConnectorPagedList(searcher, listOf(memories))
    val stats = StatsConnector(searcher)
    val filterState = FilterState()
    val connection = ConnectionHandler()

    init {
        connection += searchBox
        connection += stats
        connection += filterState.connectPagedList(memories)
    }

    override fun onCleared() {
        super.onCleared()
        searcher.cancel()
        connection.disconnect()
    }
}

我想也许有一个过滤记录的功能,SearcherSingleIndexDataSource.Factory但我没有找到这样的东西。

那么我该怎么做呢?

标签: androidkotlinsearchviewalgoliainstantsearch

解决方案


要了解如何在查询时注入过滤器,请参阅我们的FilterState 文档

在您的情况下,您可以编写如下内容:

    filterState.notify {
       add(FilterGroupID(), Filter.Facet(Attribute("userId"), "user_id_value"))
    }

让我知道这是否可以解决您的问题。


推荐阅读