How to Run Raw Queries in Elastic

To run raw queries in the Elastic backend The search engine your SmartHub instance uses to perform queries. SmartHub can be configured to use more than one search engine. use a Scripting stage as described below.

The Scripting stage is added after the Elastic Translator stage in your Query pipeline. See the graphic below.


Script example

Copy
if(Query.ExtendedProperties != null && Query.ExtendedProperties.Count > 0 && Query.ExtendedProperties["ElasticSearchRequest"] != null){

    var searchRequest = ((ElasticSearchRequest)Query.ExtendedProperties["ElasticSearchRequest"]);

    searchRequest.UseRawJson = true;
    
    var requestObject = JObject.Parse(searchRequest.RawRequestJson); 
    
    requestObject["query"] = JObject.Parse("{\"bool\":{\"must\":[{\"function_score\":{\"query\":{\"knn\":{\"escbase_fulltextcontent_vect\":{\"vector\": \"query_embeddings.tolist()\",\"k\": 1000}}},\"weight\": 0.6}}]}}");

    searchRequest.RawRequestJson =  JsonConvert.SerializeObject(requestObject);
    
}

For above script to works, you have to add: 

References Assemblies:

  • BAInsight.Elasticsearch;
  • Newtonsoft.Json;

Imported Namespaces:

  • Newtonsoft.Json;
  • Newtonsoft.Json.Linq;
  • BAInsight.Elasticsearch.Models;

In order to change elastic query you have to set the value of UseRawJson to true from ExtendedProperties of Queries (line 3).

Using requestObject (line 6), we can change the content of query with any custom raw query .