# Discourses API get just the number of search results

**URL:** https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548
**Category:** Development
**Tags:** rest-api
**Created:** [12월 21, 2017, 10:18오전 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548 "2017-12-21T10:18:45Z")
**Posts on this page:** 11
**Page:** 1

<div class="post-metadata">

### Author: ![gradam](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/gradam/32/85361_2.png) [@gradam](https://meta.discourse.org/u/gradam)
#### Post date: [12월 21, 2017, 10:18오전 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/1 "2017-12-21T10:18:45Z")

</div>

Hi. I am trying to get just the number of search results from the API.  
I have the following query `/search.json?q=query` but i just need information about how many results there are. Not blurbs, cooked, etc.  
Is it possible with discourse API?

---

<div class="post-metadata">

### Author: ![blake](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/blake/32/157322_2.png) [@blake](https://meta.discourse.org/u/blake)
#### Post date: [12월 21, 2017, 3:44오후 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/2 "2017-12-21T15:44:28Z")

</div>

I don’t think we return a “count” in the response, but it is something you can calculate yourself.

See the [search API docs](http://docs.discourse.org/#tag/Search%2Fpaths%2F~1search~1query%2Fget) for a more detailed response example, but it will look something like this:

```plaintext
{
    "posts": [],
    "topics": [],
    "users": [],
    "categories": [],
    "grouped_search_result": {}
}

```

Be default the API will return a max of 50 results. To calculate the count you need to just count the number of items in the posts array. The number items in the topics array should be the same so there is no reason to count that array too.

---

<div class="post-metadata">

### Author: ![vsoch](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/vsoch/32/124967_2.png) [@vsoch](https://meta.discourse.org/u/vsoch)
#### Post date: [9월 22, 2019, 4:31오후 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/3 "2019-09-22T16:31:54Z")

</div>

I’m trying every way I can think of to just download all the topics and posts from my site - latest and top are limited, and I’m now trying getting all categories, and doing a search for the category (akin to how I can in the site). For example, in our site if I search for Q&A #q-a [here](https://ask.cyberinfrastructure.org/search?q=Q%26A%20%23q-a) I get over 50 results. When I search for that exact string with the discourse\_api ruby gem, I get only 5:

```plaintext
irb(main):123:0> topics["posts"].length
=> 5
irb(main):124:0> topics["topics"].length
=> 5

```

Why is this not consistent with the interface and with what you are reporting? What is the easiest way to export data? I’d like to do some NLP on our site’s content and it’s proving to be very hard just to get the data. Thanks!

---

<div class="post-metadata">

### Author: ![sam](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/sam/32/102149_2.png) [@sam](https://meta.discourse.org/u/sam)
#### Post date: [9월 30, 2019, 7:59오전 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/4 "2019-09-30T07:59:50Z")

</div>

> [@vsoch](#):
>
> latest와 top은 제한이 있습니다.

latest는 페이지네이션을 지원하므로, 파라미터를 올바르게 전달하면 API를 통해 모든 토픽에 접근할 수 있습니다.

검색 기능도 페이지네이션을 지원합니다.

필요한 모든 파라미터를 파악하기 위한 입문 가이드로 [Reverse engineer the Discourse API](https://meta.discourse.org/t/how-to-reverse-engineer-the-discourse-api/20576) 을 추천합니다.

---

<div class="post-metadata">

### Author: ![vsoch](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/vsoch/32/124967_2.png) [@vsoch](https://meta.discourse.org/u/vsoch)
#### Post date: [9월 30, 2019, 4:27오후 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/5 "2019-09-30T16:27:27Z")

</div>

@sam님 감사합니다! (GET 요청만 봐도) 꽤 직관적이라는 것을 알 수 있습니다. 2페이지를 가져오려면 page 옵션을 추가로 추가하면 됩니다. 또한 `discourse_api` 함수로 "options"를 정의할 수 있다는 것도 확인할 수 있습니다:

```ruby
# frozen_string_literal: true
module DiscourseApi
  module API
    module Search
      # Returns search results that match the specified term.
      #
      # @param term [String] a search term
      # @param options [Hash] A customizable set of options
      # @option options [String] :type_filter Returns results of the specified type.
      # @return [Array] Return results as an array of Hashes.
      def search(term, options = {})
        raise ArgumentError.new("#{term} is required but not specified") unless term
        raise ArgumentError.new("#{term} is required but not specified") unless !term.empty?

        response = get('/search/query', options.merge(term: term))
        response[:body]
      end
    end
  end
end

```

그러면 - 이걸 시도해 보면, 1페이지와 2페이지에서 서로 다른 결과가 나올 것으로 예상합니다. 아니면 조금 더 간격을 두고 1페이지와 3페이지를 시도해 보겠습니다. 쿼리는 모든 Q&A 주제에 대한 것입니다:

```ruby
 query = category["name"] + " #" + category["slug"]
=> "Q&A #q-a"

```

이제 discourse\_api 클라이언트를 사용하여 1페이지와 3페이지를 가져오겠습니다:

```ruby
topics1 = client.search(query, options={"page": "1"})
topics3 = client.search(query, options={"page": "3"})

```

각 페이지의 첫 번째 주제를 확인할 수 있습니다:

```ruby
=> {"id"=>220, "title"=>"Why am I exceeding the quota?", "fancy_title"=>"Why am I exceeding the quota?", "slug"=>"why-am-i-exceeding-the-quota", "posts_count"=>3, "reply_count"=>0, "highest_post_number"=>3, "image_url"=>nil, "created_at"=>"2018-06-01T12:56:12.120Z", "last_posted_at"=>"2018-06-15T16:41:44.736Z", "bumped"=>true, "bumped_at"=>"2018-06-15T16:41:44.736Z", "unseen"=>false, "pinned"=>false, "unpinned"=>nil, "visible"=>true, "closed"=>false, "archived"=>false, "bookmarked"=>nil, "liked"=>nil, "tags"=>["storage", "quota"], "category_id"=>26, "has_accepted_answer"=>false}

irb(main):148:0> topics3['topics'][0]
=> {"id"=>220, "title"=>"Why am I exceeding the quota?", "fancy_title"=>"Why am I exceeding the quota?", "slug"=>"why-am-i-exceeding-the-quota", "posts_count"=>3, "reply_count"=>0, "highest_post_number"=>3, "image_url"=>nil, "created_at"=>"2018-06-01T12:56:12.120Z", "last_posted_at"=>"2018-06-15T16:41:44.736Z", "bumped"=>true, "bumped_at"=>"2018-06-15T16:41:44.736Z", "unseen"=>false, "pinned"=>false, "unpinned"=>nil, "visible"=>true, "closed"=>false, "archived"=>false, "bookmarked"=>nil, "liked"=>nil, "tags"=>["storage", "quota"], "category_id"=>26, "has_accepted_answer"=>false}

```

완전히 동일합니다. 이는 page 변수가 작동하지 않는다는 뜻인 것 같습니다. Chrome 개발자 도구를 검사하면, 포스트가 창에서 자동으로 로드되므로 아래로 스크롤할 때 포인트가 트리거된다는 것을 확인할 수 있으며, page=2가 올바른 파라미터임을 확인할 수 있습니다:

```plaintext
Request URL: https://ask.cyberinfrastructure.org/search?q=Q%26A%20%23q-a&page=2
Request Method: GET
Status Code: 200 (from ServiceWorker)
Referrer Policy: strict-origin-when-cross-origin

```

아니면 더 좋게, 파라미터 목록을 보면 됩니다:

```plaintext
Query String Parameters
q: Q&A #q-a
page: 2

```

이것은 폼 제출이 아니므로, 예시에서처럼 "Form Data"를 볼 수 없습니다.

---

<div class="post-metadata">

### Author: ![vsoch](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/vsoch/32/124967_2.png) [@vsoch](https://meta.discourse.org/u/vsoch)
#### Post date: [10월 18, 2019, 8:48오후 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/6 "2019-10-18T20:48:50Z")

</div>

혹시这方面的 조언이 있을까요? 제안해 주신 방법을 시도해 보았지만, 논리적인 다음 단계가 보이지 않습니다. 요청과 함께 제공된 경우, page 변수가 제대로 작동하지 않는 것 같습니다.

---

<div class="post-metadata">

### Author: ![simon](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/simon/32/339122_2.png) [@simon](https://meta.discourse.org/u/simon)
#### Post date: [10월 18, 2019, 10:27오후 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/7 "2019-10-18T22:27:25Z")

</div>

> [@vsoch](#):
>
> 요청과 함께 제공될 때 페이지 변수가 작동하지 않는 것 같습니다.

Discourse API gem은 `/search/query` 라우트를 사용합니다. 이 라우트는 [페이지네이션에 응답하지 않는 것 같습니다](https://github.com/discourse/discourse/blob/master/app/controllers/search_controller.rb#L68). Discourse UI는 `/search` 라우트를 사용합니다. 이 라우트는 [페이지네이션에 응답합니다](https://github.com/discourse/discourse/blob/master/app/controllers/search_controller.rb#L13).

브라우저에서 `http://forum.example.com/search.json?q=test`로 이동한 후 `http://forum.example.com/search.json?q=test&page=2`를 시도하여 이를 테스트할 수 있습니다.

Discourse API gem을 사용하지 않고 API 호출을 수행하는 방법을 찾아야 할 수도 있습니다. 목표가 사이트의 모든 주제와 게시글을 가져오는 것이라면, `/search` 라우트를 사용하는 것이 최선의 접근 방식이 아닌 것 같습니다.

`http://forum.example.com/c/your-category-slug.json`으로 API 호출을 시도해 볼 수 있습니다. 요청에서 해당 카테고리의 모든 주제가 반환되지 않는 경우, 요청의 `topic_list`에는 다음 페이지의 주제 라우트를 제공하는 `more_topics_url` 속성이 포함됩니다. 이는 `"/c/site-feedback?page=2"`와 같은 형태일 것입니다. JSON 데이터를 가져오려면 URL에 `.json`을 추가해야 합니다(`/c/site-feedback.json?page=2`).

---

<div class="post-metadata">

### Author: ![vsoch](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/vsoch/32/124967_2.png) [@vsoch](https://meta.discourse.org/u/vsoch)
#### Post date: [10월 19, 2019, 3:41오후 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/8 "2019-10-19T15:41:36Z")

</div>

감사합니다! 정말 완벽하게 잘 작동했고, Python의 requests를 사용하면 훨씬 _훨씬_ 쉽네요 (ruby에 더 익숙해지기 위해 일부러 어렵게 하려고 했는데, 클라이언트에 제가 필요한 기능이 없었거든요). 내보내기 작업은 거의 끝났고, 머신러닝 관련 작업은 아직 시작하지 않았지만, 제가 만든 호출에 관심이 있는 분들을 위해 간단한 스크립트는 여기에 있습니다: [GitHub - hpsee/discourse-cluster: Simple scripts to export posts for a discourse category, and do a clustering · GitHub](https://github.com/hpsee/discourse-cluster). 곧 멋진 클러스터링 작업을 해볼 수 있으면 좋겠습니다!

---

<div class="post-metadata">

### Author: ![vsoch](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/vsoch/32/124967_2.png) [@vsoch](https://meta.discourse.org/u/vsoch)
#### Post date: [10월 20, 2019, 5:30오후 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/9 "2019-10-20T17:30:35Z")

</div>

다시 한번 @sam님과 @simon님께 감사드립니다. 혹시 다른 분들도 주제(topic)를 간단하게 내보내는 것, 혹은 (더 나아가) d3를 이용해 클러스터링과 시각화를 해보고 싶으시다면, 과정을 정리한 짧은 글을 작성했습니다: [AskCI Discourse Clustering | Vsoch](https://vsoch.github.io/2019/askci-discourse-cluster/). 그리고 앞서 링크드 리포지토리에 시작에 필요한 모든 자료가 있으니 참고해 주세요.

---

<div class="post-metadata">

### Author: ![system](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/system/32/443519_2.png) [@system](https://meta.discourse.org/u/system)
#### Post date: [6월 29, 2023, 9:14오후 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/10 "2023-06-29T21:14:52Z")

</div>



---

<div class="post-metadata">

### Author: ![Canapin](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/canapin/32/119591_2.png) [@Canapin](https://meta.discourse.org/u/Canapin)
#### Post date: [6월 30, 2023, 7:30오전 UTC](https://meta.discourse.org/t/discourses-api-get-just-the-number-of-search-results/76548/11 "2023-06-30T07:30:55Z")

</div>


