简体   繁体   中英

First letter match in elasticsearch aggregations

I'm migrating my elasticsearch from using facets to using aggregations, and I want to create a query where the aggregations represent all the creator names that begin with a certain letter.

I've created a nested index like so:

 indexes creators, type: 'nested' do
  indexes :name, type: 'string', analyzer: 'caseinsensitive', index: 'not_analyzed'
end

The following query will return all the items where a creator's name begins with a "b". Great working so far.

      {
        "query": {
            "filtered": {
                "query": {"match_all": {}},
                "filter": {
                    "nested": {
                        "path": "creators",
                        "query": {
                            "prefix": {
                                "creators.name": {
                                    "value": "b"
                                }
                            }
                        }
                    }
                }
            }
        },
        "aggregations": {
          "creators": {
             "nested": {
                "path": "creators"
             },
             "aggs": {
                "name": {
                   "terms": {
                      "field": "creators.name",
                      "size": 100
                   }
                }
             }
          }
       }
    }

However, the aggregations part of the query returns ALL of the aggregations for the results, including instances creator names that do not begin with a "b." For instance, if I had an item with two creators:

           "creators": [
              {
                 "name": "Beyonce"
              },
              {
                 "name": "JayZ"
              }
           ],

The aggregation results would include both JayZ and Beyonce. Like most people, I only want Beyonce.

Try this query and see how it goes:

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "nested": {
          "path": "creators",
          "query": {
            "prefix": {
              "creators.name": {
                "value": "b"
              }
            }
          }
        }
      }
    }
  },
  "aggregations": {
    "creators": {
      "nested": {
        "path": "creators"
      },
      "aggs": {
        "NAME": {
          "filter": {
            "prefix": {
              "creators.name": "b"
            }
          },
          "aggs": {
            "name": {
              "terms": {
                "field": "creators.name",
                "size": 100
              }
            }
          }
        }
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM