본문 바로가기
개발/ALGOLIA

알고리아 Managing Results(3-28)

by dev_caleb 2022. 3. 5.
728x90

Filter an Array

https://www.algolia.com/doc/guides/managing-results/refine-results/filtering/how-to/filter-arrays/

 

Filter an array | Algolia

How to filter an array of filter values.

www.algolia.com

 

 

What’s an array in the context of filtering? When you start filtering, many of your filter attributes will take only a single value per record. For example, in a book index, if you filter by type of story (novel, short story), you only need to tag each book with a single value - normally, a book can’t be both a novel and a short story. On the other hand, other attributes, like genre, can often contain multiple values: the same book can be included in the “crime”, “comedy”, and “historical” genres. The genre attribute therefore needs to be an array.

Generally speaking, any attribute that contains a list of values for a single record needs to be set up as an array. A single value attribute takes a string as a value; multiple values require an array, whose syntax changes depending on the programming language used.

필터링의 맥락에서 배열은 무엇입니까? 필터링을 시작하면 많은 필터 특성이 레코드당 하나의 값만 사용합니다. 예를 들어, 책 색인에서 이야기 유형(소설, 단편)으로 필터링하면 각 책에 단일 값만 태그하면 됩니다. 일반적으로 책은 소설과 단편 둘 다일 수 없습니다. 반면에, 장르와 같은 다른 속성들은 종종 여러 가치를 포함할 수 있다: 같은 책은 범죄, 희극, 역사 장르에 포함될 수 있다. 따라서 장르 속성은 배열이어야 합니다.
일반적으로 단일 레코드에 대한 값 목록을 포함하는 속성은 배열로 설정해야 합니다. 단일 값 특성은 문자열을 값으로 사용합니다. 다중 값에는 사용되는 프로그래밍 언어에 따라 구문이 변경되는 배열이 필요합니다.

 

 

Dataset example#

To illustrate how to use an array, consider the following use case. Imagine customers have several brick-and-mortar bookstores in their neighborhood. They also use an ecommerce store. On this website, customers can order books, but also check if the same books are available in their nearby physical stores, so they can come and pick them up themselves. In your search, you may want to add a filtering option to let them filter by book genre and by store.

Since you want to filter by category and physical store, you can create two array attributes, storeand categories. Each contains the list of all available options.

 

배열을 사용하는 방법을 설명하려면 다음 사용 사례를 고려하십시오. 고객들이 이웃에 몇 개의 오프라인 서점을 가지고 있다고 상상해 보세요. 그들은 또한 전자상거래 상점을 이용한다. 이 사이트에서는 고객이 책을 주문할 수 있을 뿐 아니라 가까운 실제 매장에 같은 책이 있는지도 확인할 수 있어 직접 찾아올 수 있다. 검색에서 책 장르 및 상점별로 필터링할 수 있는 필터링 옵션을 추가할 수 있습니다.
category 및 실제 저장소를 기준으로 필터링하려는 경우 저장소 및 category라는 두 가지 배열 특성을 생성할 수 있습니다. 각 옵션에는 사용 가능한 모든 옵션 목록이 포함되어 있습니다.

 

[
  {
    "title": "Harry Potter and the Philosopher's Stone",
    "author": "J. K. Rowling",
    "popularity": 1000,
    "store": [
      "The Corner Bookshop",
      "Gibert Joseph Barbès",
      "Gibert Joseph Paris 13 - Grande Bibliothèque"
    ],
    "categories": [
      "fantasy",
      "science fiction",
      "children's literature"
    ]
  },
  {
    "title": "The World as It Is",
    "author": "Ben Rhodes",
    "popularity": 900,
    "store": [
      "The Corner Bookshop"
    ],
    "categories": [
      "history",
      "politics"
    ]
  },
  [...]
]

 

You now have the necessary data to leverage Algolia’s filtering capabilities. You could for example retrieve all matching books that are about politics and are in stock in the The Corner Bookshop store.

 

이제 Algolia의 필터링 기능을 활용하는 데 필요한 데이터를 가졌습니다. 예를 들어, 정치에 관한 책이며 코너 서점에 비치되어 있는 모든 일치하는 책을 검색할 수 있습니다.

 

 

Configuring attributesForFaceting (at indexing time)#

Before you can filter on your array attributes, you first need to set them as attributes for faceting.

어레이 특성을 필터링하려면 먼저 이러한 특성을 패싱 특성으로 설정해야 합니다.

Using the API

First, you need to set categories and store as attributesForFaceting. This happens at indexing time.

index.setSettings({
  attributesForFaceting: [
    'categories', // or 'filterOnly(categories)' for filtering purposes only
    'store' // or 'filterOnly(store)' for filtering purposes only
  ]
}).then(() => {
  // done
});

 

Using the dashboard#

You can set your attribute for faceting in your Algolia dashboard.

  1. Select the Search product icon on your dashboard and then select your index.
  2. Click the Configuration tab.
  3. In the Facets subsection of Filtering and Faceting, click the “Add an attribute” button and select your categories attribute from the dropdown.
  4. Don’t forget to save your changes.

Applying an array filter (at search time)#

Using the API#

Now, you can apply your filters. You can only filter results at query time, not at indexing time. For this, you need to use the filters parameter in your search code.

index.search('harry', {
  filters: 'categories:politics AND store:Gibert Joseph Saint-Michel'
}).then(({ hits }) => {
  console.log(hits);
});

Note that you can also use facetFilters to do the same thing.

 

Using the dashboard

Regarding filters, you can’t set them directly in the dashboard since you can only filter at query time. Yet, you can test for specific filters in the dashboard before using them in your search code.

필터의 경우 쿼리 시에만 필터링할 수 있으므로 대시보드에서 직접 설정할 수 없습니다. 그러나 검색 코드에 사용하기 전에 대시보드에서 특정 필터를 테스트할 수 있습니다.

  1. Go to your dashboard and select your index. This should take you automatically to the Browsesection.
  2. Click the “Add Query Parameter” button, which is just below the search bar.
  3. Go to the Filters tab (it should be the default).
  4. In the Facet filters input, type categories: politics and hit enter. Now type store: The Corner Bookshop and hit enter.
  5. Click “Apply”.

The results in your dashboard search will be political and available at The Corner Bookshop store.

You can also test for regular filters (with the filters feature). To do this go to the Custom tab of the Add Query Parameter input menu and add your filter as JSON:

대시보드 검색 결과는 정치적이고 코너 서점에서 구할 수 있습니다.
필터 기능을 사용하여 일반 필터를 테스트할 수도 있습니다. 이렇게 하려면 Add Query Parameter(쿼리 매개 변수 추가) 입력 메뉴의 Custom(사용자 정의) 탭으로 이동하여 필터를 JSON으로 추가합니다.

 

 

{
  "filters": "categories:politics AND store:'The Corner Bookshop'"
}

 

 

Filter By Null or Missing Attributes

https://www.algolia.com/doc/guides/managing-results/refine-results/filtering/how-to/filter-by-null-or-missing-attributes/

 

Filter by null or missing attributes | Algolia

How to filter on records that don't contain the filter values.

www.algolia.com

What happens when your index contains an attribute that isn’t present in all records?

For example, consider an online book store where people can buy, but also rate books, from 0 to 5. Any record without the rating attribute is assumed not to be rated yet.

인덱스에 일부 레코드에는 없는 속성이 포함되어 있으면 어떻게 될까요?
예를 들어, 사람들이 책을 살 수 있을 뿐만 아니라 0부터 5까지 등급을 매길 수 있는 온라인 서점을 생각해 보자. 등급 속성이 없는 기록은 아직 등급이 매겨지지 않은 것으로 가정합니다.

Objects are schemaless, so this isn’t a problem until you want to filter on records with and without a specific attribute.

Generally speaking, selective filtering becomes a problem when the existence or non-existence of a filter value actually means something. The Algolia engine doesn’t support filtering on null value or missing attributes. In other words, in the preceding example, if you wanted to combine books with a specific rating and books that aren’t yet rated in the same filtering statement, this would require some modification of the data.

개체는 스키마가 없으므로 특정 특성이 있는 레코드와 없는 레코드를 필터링할 때까지 문제가 되지 않습니다.
일반적으로 선택적 필터링은 필터 값의 존재 또는 비존재가 실제로 무언가를 의미할 때 문제가 됩니다. Algolia 엔진은 null 값 또는 특성 누락에 대한 필터링을 지원하지 않습니다. 다시 말해, 이전 예에서 특정 등급을 가진 책과 동일한 필터링 문에서 아직 등급이 지정되지 않은 책을 결합하려는 경우 데이터를 수정해야 합니다.

There are two approaches:

  • using the _tags attribute,
  • using a boolean attribute.

Dataset#

In the three following records: one has a correctly filled rating attribute, a second has a null rating, and the third doesn’t have a rating:

[
  {
    "title": "The Shining",
    "author": "Stephen King",
    "rating": 5
  },
  {
    "title": "Fantastic Beasts and Where to Find Them",
    "author": "J. K. Rowling",
    "rating": null
  },
  {
    "title": "Run Away",
    "author": "Harlan Coben"
  }
]

Here, only the first record has a rating. The other two are assumed not to have been rated yet. Note that a null or nonexistent attribute is different from zero, which represents a book with a rating equal to 0.

 

 

Creating a tag#

At indexing time, you can compute a tag that specifies what it means when the attribute is present, set, or absent.

인덱싱 시 특성이 있거나, 설정되거나, 없는 경우의 의미를 지정하는 태그를 계산할 수 있습니다.

[
  {
    "title": "The Shining",
    "author": "Stephen King",
    "rating": 5,
    "_tags": ["is_rated"]
  },
  {
    "title": "Fantastic Beasts and Where to Find Them",
    "author": "J. K. Rowling",
    "rating": null,
    "_tags": ["is_not_rated"]
  },
  {
    "title": "Run Away",
    "author": "Harlan Coben",
    "_tags": ["is_not_rated"]
  }
]
 
To search for records that don’t have the attribute or attribute value present, you can now use tags filtering:
특성 또는 특성 값이 없는 레코드를 검색하려면 이제 태그 필터링을 사용할 수 있습니다.
 
index.search('query', {
  filters: '_tags:is_not_rated'
}).then(({ hits }) => {
  console.log(hits);
});
 

Creating a boolean attribute#

At indexing time, you can compute a boolean attribute named is_rated:

[
  {
    "title": "The Shining",
    "author": "Stephen King",
    "rating": 5,
    "is_rated": true
  },
  {
    "title": "Fantastic Beasts and Where to Find Them",
    "author": "J. K. Rowling",
    "rating": null,
    "is_rated": false
  },
  {
    "title": "Run Away",
    "author": "Harlan Coben",
    "is_rated": false
  }
]​
 
 
To search for records that don’t have the attribute or attribute value present, you can now useboolean filtering:
 
index.search('query', {
  filters: 'is_rated = 0'
}).then(({ hits }) => {
  console.log(hits);
});​
 
 
 

 

 

 

 

728x90

'개발 > ALGOLIA' 카테고리의 다른 글

알고리아 Managing Results(3-30)  (0) 2022.03.05
알고리아 Managing Results(3-29)  (0) 2022.03.05
알고리아 Managing Results(3-27)  (0) 2022.03.05
알고리아 Managing Results(3-26)  (0) 2022.03.05
알고리아 Managing Results(3-25)  (0) 2022.03.05