2015-05-26 13 views
9

Ich bin ein Neuling in ElasticSearch.Elastische Suche Summe Aggregation mit Gruppe von und wo Bedingung

Wir bewegen derzeit unseren Code von der relationalen DB zu ElasticSearch. Daher konvertieren wir unsere Abfragen im ElasticSearch-Abfrageformat.

Ich suche Elasticsearch Äquivalent Abfrage unten -

SELECT Color, SUM(ListPrice), SUM(StandardCost) 
FROM Production.Product 
WHERE Color IS NOT NULL 
    AND ListPrice != 0.00 
    AND Name LIKE 'Mountain%' 
GROUP BY Color 

Kann mir jemand bieten das Beispiel Elasticsearch Abfrage für oben?

Antwort

18

würden Sie haben einen products Index mit einem product Typ Dokumente, deren Mapping wie dies auf der Grundlage Ihrer Abfrage oben aussehen könnte:

curl -XPUT localhost:9200/products -d ' 
{ 
    "mappings": { 
    "product": { 
     "properties": { 
     "Color": { 
      "type": "string" 
     }, 
     "Name": { 
      "type": "string" 
     }, 
     "ListPrice": { 
      "type": "double" 
     }, 
     "StandardCost": { 
      "type": "double" 
     } 
     } 
    } 
    } 
}' 

Dann ist die ES-Abfrage entspricht dem SQL würden Sie gab oben aussehen dies:

{ 
    "query": { 
    "filtered": { 
     "query": { 
     "query_string": { 
      "default_field": "Name", 
      "query": "Mountain*" 
     } 
     }, 
     "filter": { 
     "bool": { 
      "must_not": [ 
      { 
       "missing": { 
       "field": "Color" 
       } 
      }, 
      { 
       "term": { 
       "ListPrice": 0 
       } 
      } 
      ] 
     } 
     } 
    } 
    }, 
    "aggs": { 
    "by_color": { 
     "terms": { 
     "field": "Color" 
     }, 
     "aggs": { 
     "total_price": { 
      "sum": { 
      "field": "ListPrice" 
      } 
     }, 
     "total_cost": { 
      "sum": { 
      "field": "StandardCost" 
      } 
     } 
     } 
    } 
    } 
} 
+0

Danke. es funktionierte. –

+0

Wie wird nach der Summe der Aggregation sortiert? Grundsätzlich in diesem Beispiel nach Total_Price zu bestellen? –

+0

@ErdalG. In der Aggregation "Terms" können Sie folgendes hinzufügen: '" order ": {" total_price ":" desc "}' – Val