본문 바로가기
개발/ALGOLIA

알고리아 Managing Results(3-27)

by dev_caleb 2022. 3. 5.
728x90

Filter By Date

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

 

Filter by date | Algolia

How to filter by date.

www.algolia.com

 

 

Dates aren’t only useful for sorting. You can also leverage them to filter search results on a specific date range. Imagine you have a blog, and you want to provide time-based filters. For example, you may want to allow users to filter on recent posts, or only see posts from a certain period.

날짜는 분류에만 유용한 것이 아닙니다. 또한 특정 날짜 범위의 검색 결과를 필터링하는 데 사용할 수 있습니다. 블로그가 있고 시간 기반 필터를 제공하려고 합니다. 예를 들어, 사용자가 최근 게시물을 필터링하거나 특정 기간의 게시물만 볼 수 있도록 허용할 수 있습니다.

 

 

 

Modifying the data: an example#

Before#

Let’s say we have an index called articles that looks like this:

 

[
  {
    "title": "Algolia's Global Roadshow",
    "author": "Ryan Chen",
    "excerpt": "We've heard it from experts, industry surveys, and our most successful customers: search and discovery are key to moving the digital conversation forward.",
    "date": "2018-10-17"
  },
  {
    "title": "Black Friday & Site Search: small tips, big difference",
    "author": "Matthieu Blandineau",
    "excerpt": "It's no surprise that during the holiday season, Black Friday & Cyber Monday are absolutely critical events for any ecommerce business. According to Adobe, online retailers earned $108.15B between Nov 1 and Dec 31 2017, up 13.8% from 2016. Only in the U.S.",
    "date": "2018-10-05"
  },
  {
    "title": "For better school projects, a partnership with GitHub",
    "author": "Jessica West",
    "excerpt": "Hello GitHubbers and Algolians alike! We have some exciting news we'd like to share with you. Algolia is so pleased to announce that we have partnered with GitHub's Student Developer Pack to help students build search functionality into their projects freely and effortlessly 🎉.",
    "date": "2018-09-18"
  }
]

Algolia can handle filtering on date, as long as you format them properly. This means you first need to transform your date attribute into Unix timestamps, as numeric values.

Algolia는 제대로 포맷하기만 하면 날짜별로 필터링을 처리할 수 있습니다. 이것은 먼저 날짜 속성을 숫자 값으로 Unix 타임스탬프로 변환해야 함을 의미합니다.

 

 

After#

Before we can filter on date, we need to add the date as a Unix timestamp. We don’t have to remove or change date; instead, we can add a date_timestamp attribute with the proper format.

Note that this attribute needs to be a numeric value for Algolia to be able to sort on it.

[
  {
    "title": "Algolia's Global Roadshow",
    "author": "Ryan Chen",
    "excerpt": "We've heard it from experts, industry surveys, and our most successful customers: search and discovery are key to moving the digital conversation forward.",
    "date": "2018-10-17",
    "date_timestamp": 1539734400
  },
  {
    "title": "Black Friday & Site Search: small tips, big difference",
    "author": "Matthieu Blandineau",
    "excerpt": "It's no surprise that during the holiday season, Black Friday & Cyber Monday are absolutely critical events for any ecommerce business. According to Adobe, online retailers earned $108.15B between Nov 1 and Dec 31 2017, up 13.8% from 2016. Only in the U.S.",
    "date": "2018-10-05",
    "date_timestamp": 1538697600
  },
  {
    "title": "For better school projects, a partnership with GitHub",
    "author": "Jessica West",
    "excerpt": "Hello GitHubbers and Algolians alike! We have some exciting news we'd like to share with you. Algolia is so pleased to announce that we have partnered with GitHub's Student Developer Pack to help students build search functionality into their projects freely and effortlessly 🎉.",
    "date": "2018-09-18",
    "date_timestamp": 1537228800
  }
]

Applying a date filter#

Now that Algolia can understand our dates, we can use the filters attribute on them at search time to only retrieve some results.

이제 Algolia가 우리의 날짜를 이해할 수 있으므로, 우리는 검색 시 필터 속성을 사용하여 일부 결과만 검색할 수 있습니다.

Recent posts

Imagine we want to let users filter on most recent articles. First, you need to define what recentmeans for you. It may vary depending on your use case, the frequency at which you add new content, etc.

Let’s say that in our case, a recent article means an article that’s less than a week old. This means we need to set a filter that excludes records which date_timestamp is greater than now minus one week.

Algolia filters use a SQL-like syntax, which allows you to use comparison operators.

사용자가 대부분의 최신 기사를 필터링할 수 있도록 한다고 상상해 보십시오. 먼저, 당신에게 최근 의미가 무엇인지 정의해야 합니다. 사용 사례, 새로운 콘텐츠 추가 빈도 등에 따라 달라질 수 있습니다.
우리의 경우 최근 기사가 1주일도 안 된 기사를 의미한다고 치자. 즉, 지금보다 큰 date_timestamp에서 일주일을 뺀 레코드를 제외하는 필터를 설정해야 합니다.
Algolia 필터는 비교 연산자를 사용할 수 있는 SQL과 유사한 구문을 사용합니다

 

const d = new Date()

index.search('query', {
  filters: `date_timestamp > ${Math.floor(d.setDate(d.getDate() - 7) / 1000)}`
}).then(({ hits }) => {
  console.log(hits);
});

Posts from a particular month#

Now imagine we want only to retrieve posts from October 2018. We can achieve this by setting a range filter that spans the full month, by providing Unix timestamps for the first and last day of the month.

index.search('query', {
  filters: 'date_timestamp:1538352000 TO 1540944000'
}).then(({ hits }) => {
  console.log(hits);
});

 

You may also want to exclude a particular month, or generally search for all posts but a specific range. For this, you can combine numeric ranges with it to the NOT boolean operator.

 

index.search('query', {
  filters: 'NOT date_timestamp:1538352000 TO 1540944000'
}).then(({ hits }) => {
  console.log(hits);
});

Closest records first(가장 가까운 레코드 먼저)

You can combine filters to a sorting strategy to go even further. Imagine you now have an index of concert dates. A nice search experience could be to get search results order from sooner to later, so that the end user would get upcoming concerts first.

First, you need to sort records by ascending date so you keep later events low in search results.


필터를 정렬 전략과 결합하여 한 단계 더 나아갈 수 있습니다. 이제 콘서트 날짜의 인덱스가 생겼다고 상상해 보세요. 빠른 시일 내에 검색 결과 순서를 받아 최종 사용자가 다가오는 콘서트를 먼저 받을 수 있도록 하는 것이 멋진 검색 경험일 수 있다.
먼저 레코드를 오름차순 날짜별로 정렬하여 검색 결과에서 이후 이벤트를 낮게 유지해야 합니다.

 

index.setSettings({
  ranking: [
    "asc(date_timestamp)",
    "typo",
    "geo",
    "words",
    "filters",
    "proximity",
    "attribute",
    "exact",
    "custom"
  ]
}).then(() => {
  // done
});

 

Then, you can filter out every record with past dates. Combined to the sorting setting, this returns events from closest to the current date, to later in time.

 

const nowTimestamp = Date.now();

index.search('query', {
  filters: `date_timestamp >= ${nowTimestamp}`
}).then(({ hits }) => {
  console.log(hits);
});

 

To learn more on how to sort an index by date, see Sort an Index by Date.

 

 

 

 

 

728x90

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

알고리아 Managing Results(3-29)  (0) 2022.03.05
알고리아 Managing Results(3-28)  (0) 2022.03.05
알고리아 Managing Results(3-26)  (0) 2022.03.05
알고리아 Managing Results(3-25)  (0) 2022.03.05
알고리아 Managing Results(3-24)  (0) 2022.03.04