

# Configuring Expressions in Amazon CloudSearch
<a name="configuring-expressions"></a>

You can define numeric expressions and use them to sort search results. Expressions can also be returned in search results. You can add expressions to the domain configuration or define expressions within search requests. 

**Topics**
+ [Writing Expressions for Amazon CloudSearch](#writing-expressions)
+ [query time expressions](defining-expressions-in-requests.md)
+ [Configuring Reusable Expressions for a Search Domain in Amazon CloudSearch](configuring-reusable-expressions.md)
+ [Comparing Expressions in Amazon CloudSearch](comparing-expressions.md)

## Writing Expressions for Amazon CloudSearch
<a name="writing-expressions"></a>

Amazon CloudSearch expressions can contain:
+ Single value, sort enabled numeric fields (`int`, `double`, `date`). (You must specify a specific field, wildcards are not supported.)
+ Other expressions
+ The `_score` variable, which references a document's relevance score
+ The `_time` variable, which references the current epoch time
+ The `_rand` variable, which returns a randomly generated value
+ Integer, floating point, hex, and octal literals
+ Arithmetic operators: `+ - * / %`
+ Bitwise operators:` | & ^ ~ << >> >>>`
+ Boolean operators (including the ternary operator):` && || ! ?: `
+ Comparison operators:` < <= == >= > `
+ Mathematical functions: `abs ceil exp floor ln log10 logn max min pow sqrt `
+ Trigonometric functions: `acos acosh asin asinh atan atan2 atanh cos cosh sin sinh tanh tan`
+ The `haversin` distance function

[ JavaScript order of precedence rules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table) apply for operators. You can override operator precedence by using parentheses.

Shortcut evaluation is used when evaluating logical expressions—if the value of the expression can be determined after evaluating the first argument, the second argument is not evaluated. For example, in the expression `a || b`, `b` is only evaluated if `a` is not true.

Expressions always return an integer value from 0 to the maximum 64-bit signed integer value (2^63 - 1). Intermediate results are calculated as double-precision floating point values and the return value is rounded to the nearest integer. If the expression is invalid or evaluates to a negative value, it returns 0. If the expression evaluates to a value greater than the maximum, it returns the maximum value. 

Expression names must begin with a letter and be at least 3 and no more than 64 characters long. The following characters are allowed: a-z (lower-case letters), 0-9, and \$1 (underscore). The name *score* is reserved and cannot be used as an expression name.

For example, if you define an `int` field named *popularity* for your domain, you could use that field in conjunction with the default relevance `_score` to construct a custom expression. 

```
(0.3*popularity)+(0.7*_score)
```

Note that this simple example assumes that the popularity ranking and the relevance \$1score values are in about the same range. To tune your expressions for ranking results, you need to do some testing to determine how to weight the components of your expressions to get the results you want. 

### Using Date Fields in Amazon CloudSearch Expressions
<a name="using-dates-in-expressions"></a>

The value from a `date` field is stored as an epoch time with millisecond resolution. This means you can use the mathematical and comparison operators to construct expressions using dates stored in your documents and the current epoch time (`_time`). For example, using the following expression to sort search results from the movies domain pushes movies with recent release dates toward the top of the list. 

```
_score/(_time - release_date)
```

# Defining Amazon CloudSearch Expressions in Search Requests
<a name="defining-expressions-in-requests"></a>

You can define and use expressions directly within a search request so that you can iterate quickly while you fine-tune expressions that you use to sort results. By defining an expression within a search request, you can also incorporate contextual information into the expression, such as the user's geographic location. You can override an expression defined in the domain configuration by defining an expression with the same name within a search request.

When you define an expression within a search request, it is not stored as part of your domain configuration. If you want to use the expression in other requests, you must define the expression in each request or add the expression to your domain configuration. Defining an expression in every request rather than adding it to the domain configuration increases the request overhead, which can result in slower response times and potentially increase the cost of running your domain. For information about adding expressions to the domain configuration, see [Configuring Expressions](configuring-expressions.md). 

You can define and use multiple expressions in a search request. The definition of an expression can reference other expressions defined within the request, as well as expressions configured as part of the domain configuration. 

There are no restrictions on how you can use expressions that you define in a search request. You can use the expression to sort the search results, define other expressions, or return computed information in the search results. 

**To define an expression in a search request**

1. Use the `expr.NAME` parameter, where NAME is the name of the expression you are defining. For example: 

   ```
   expr.rank1=log10(clicks)*_score
   ```

1. To use the expression to sort the results, specify the name of the expression with the `sort` parameter:

   ```
   search?q=terminator&expr.rank1=log10(clicks)*_score&sort=rank1 desc
   ```

1. To include the computed value in the search results, add the expression to the list of `return` fields: 

   ```
   search?q=terminator&expr.rank1=log10(clicks)*_score&sort=rank1 desc&return=rank1
   ```

 For example, the following request creates two expressions that are used to sort the results and returns one of them in the search results:

```
search?q=terminator&expr.rank1=sin( _score)&expression.rank2=cos( _score)&sort=rank1 desc,rank2 desc&return=title,_score,rank2
```

# Configuring Reusable Expressions for a Search Domain in Amazon CloudSearch
<a name="configuring-reusable-expressions"></a>

When you define an expression in a domain's configuration, you can reference the expression in any search request. Adding an expression to the domain configuration reduces the overhead of specifying it in every request, and helps maximize response times and minimize costs. 

When you add an expression to your domain configuration, it takes some time for the change to be processed and the new expression to become active. To quickly test changes to an expression, you can define and use the expression directly in a search request, as described in [Defining Expressions in Search Requests](defining-expressions-in-requests.md). After you have finished testing and tuning an expression, you should add it to your domain configuration. 

**Topics**
+ [Amazon CloudSearch console](#configuring-expressions-console)
+ [aws cloudsearch define-expression](#configuring-expressions-clt)
+ [DefineRankExpression](#configuring-expressions-sdk)

## Configuring Expressions Using the Amazon CloudSearch Console
<a name="configuring-expressions-console"></a>

**To configure an expression**

1. Open the Amazon CloudSearch console at [https://console.aws.amazon.com/cloudsearch/home](https://console.aws.amazon.com/cloudsearch/home).

1. From the left navigation pane, choose **Domains**.

1. Choose the name of the domain to open its configuration.

1. Go to the **Advanced search options** tab.

1. In the **Expressions** pane, choose **Add expression**.

1. Enter a name for the new expression.

1. For **Value**, enter the numerical expression that you want to evaluate at search time. You can select **Insert** to add special values and mathematical and trigonometric functions.

1. Choose **Save**.

## Configuring Amazon CloudSearch Expressions Using the AWS CLI
<a name="configuring-expressions-clt"></a>

You use the `aws cloudsearch define-expression` command to define computed expressions for a domain.

**To configure an expression**
+ Run the `aws cloudsearch define-expression` command to define a new expression. You specify a name for the expression with the `--name` option, and the numeric expression that you want to evaluate with the `--expression` option. For example, the following request creates an expression called `popularhits` that takes into account a document's `popularity` and relevance `_score`.

  ```
  aws cloudsearch define-expression --domain-name movies --name popularhits --expression '((0.3*popularity)/10.0)+(0.7* _score)'
  
  {
      "Expression": {
          "Status": {
              "PendingDeletion": false, 
              "State": "Processing", 
              "CreationDate": "2014-05-01T01:15:18Z", 
              "UpdateVersion": 52, 
              "UpdateDate": "2014-05-01T01:15:18Z"
          }, 
          "Options": {
              "ExpressionName": "popularhits", 
              "ExpressionValue": "((0.3*popularity)/10.0)+(0.7* _score)"
          }
      }
  }
  ```

## Configuring Expressions Using the Amazon CloudSearch Configuration API
<a name="configuring-expressions-sdk"></a>

The AWS SDKs (except the Android and iOS SDKs) support all of the Amazon CloudSearch actions defined in the Amazon CloudSearch Configuration API, including `DefineExpression`. For more information about installing and using the AWS SDKs, see [AWS Software Development Kits](http://aws.amazon.com/code).

# Comparing Expressions in Amazon CloudSearch
<a name="comparing-expressions"></a>

 You can use the Amazon CloudSearch console to compare expressions and see how changes to the expression and field weights affect how Amazon CloudSearch sorts search results.

**To compare expressions**

1. Open the Amazon CloudSearch console at [https://console.aws.amazon.com/cloudsearch/home](https://console.aws.amazon.com/cloudsearch/home).

1. In the left navigation pane, choose **Domains**.

1. Choose the name of the domain to open its configuration.

1. Choose **Actions**, **Compare expressions**.

1. In the **Search** box, enter the terms you want to search for. Amazon CloudSearch ranks the search results using the specified expressions and weights. It refreshes the results whenever you make changes to the expressions or weights.

1. In each expression editor, specify the rank expressions to compare. You can add new expressions or select an existing expression from the **Saved expressions** menu. Amazon CloudSearch evaluates new expressions when you submit a search request.

1. Specify the field weights to use for each expression. You can also edit the field weights directly in the expression. Field weights must be in the range 0.0 to 10.0, inclusive. By default, the weight for all fields is set to 1.0. You can set individual field weights to control how much matches in particular text or literal fields affect a document's relevance \$1score. You can also change the default weight.
**Note**  
Adjusting field weights only affects result ranking if the expression references the `_score` value. You can modify the expression to change how the weight relevance `_score` contributes to a document's overall ranking. For more information, see [Using Relative Field Weighting to Customize Text Relevance](weighting-fields.md).

1. Choose **Run**.

1. The search results for the two expressions are shown side-by-side. (If the expression is empty, the results are sorted according to the default relevance `_score`.) Four icons highlight the differences:  
![\[Green upward-pointing arrow icon indicating an increase or positive trend.\]](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/images/cloudsearch-console-green-up-arrow.png) Green up arrow  
 The document is ranked higher in the search results using the second expression.   
![\[Red downward-pointing arrow icon indicating a download or direction.\]](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/images/cloudsearch-console-red-down-arrow.png) Red down arrow  
 The document is ranked lower in the search results using the second expression.   
![\[Yellow plus sign icon typically used to indicate an add or create action.\]](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/images/cloudsearch-console-yellow-plus.png) Yellow plus  
 The document is included in the search results using the second expression, but was omitted from the search results using the first expression.  
![\[Red circular sign with a white horizontal bar, indicating prohibition or restriction.\]](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/images/cloudsearch-console-red-minus.png) Red minus  
 The document was omitted from the search results using the second expression, but was included in the search results using the first expression. 

**Note**  
You can save expressions to your domain configuration directly from the **Compare expressions** pane. To save either expression, choose **Save expression**.