Search code examples
ruby-on-railselasticsearchfacetrubber-band

Faceting with Rubberband


I am implementing ElasticSearch in a Ruby-on-Rails 2.3 application with the RubberBand gem. I am trying to return facets but I can't seem to find methods that I can use for this purpose. I've looked through the documentation and source.

Does anyone know if it's possible with rubberband?


Solution

  • This issue might have what you are looking for:

    https://github.com/grantr/rubberband/issues/4

    q = {
      "query"=> {
        "filtered"=> {
          "query"=> { 
            "match_all"=> {}
          },
          "filter"=> {
            "term"=> {
              "client_id"=> "717",
              "product_id"=> "1"
            }
          }
        }
      },
      "facets"=> {
        "shipped_to_state_counts"=> {
          "terms"=> {
            "field"=> "state",
            "size"=> "500"
          }
        }
      }
    }
    

    EDIT: (simpler query, lucene syntax)

    NOTE: These are not the same queries, per elasticsearch documentation:

    There’s one important distinction to keep in mind. While search queries restrict both the returned documents and facet counts, search filters restrict only returned documents — but not facet counts.

    q = {
      "query"=> {
        "query_string"=> {
          "query"=> "client_id:717 AND product_id:1"
        }
      },
      "facets"=> {
        "shipped_to_state_counts"=> {
          "terms"=> {
            "field"=> "state",
            "size"=> "500"
          }
        }
      }
    }
    

    END EDIT

    results = client.search(q)
    facets = results.facets
    
    =>
    {
      "shipped_to_state_counts"=> {
        "_type"=> "terms",
        "missing"=> 0,
        "total"=> 1873274,
        "other"=> 0,
        "terms"=> [
          {
            "term"=> "MO",
            "count"=> 187327
          },
          {
            "term"=> "FL",
            "count"=> 17327
          }
        ]
      }
    }