简体   繁体   中英

group search results in elasticsearch

Say, I want to display certain results on specific part of the my page. Is there a way to group my search results from elastic based on my query.

Eg

1.

GET /my_index/_search
{
 "query": {
     "bool": {
         "must": [
            {"match": {"field1": "value1"}},
            {"match": {"field7": "value7"}}
          ]
      }
   }
}

2.

GET /my_index/_search
{
 "query": {
     "bool": {
         "must": [
            {"match": {"field2": "value2"}}
          ]
      }
   }
}

is it possible to combine these 2 into one call to elastic and just group the results?

You can send multiple searches in one request with Multi Search API

This is exposed in NEST

var pool = new SingleNodeConnectionPool(new Uri($"http://localhost:9200"));
var defaultIndex = "my_index";
var connectionSettings = new ConnectionSettings(pool)
        .DefaultIndex(defaultIndex)

var client = new ElasticClient(connectionSettings);

var multiSearchResponse = client.MultiSearch(ms => ms
    .Index(defaultIndex)
    .Search<Document>("search1", s => s
        .AllTypes()
        .Query(q => q
            .Match(m => m
                .Field(f => f.Field1)
                .Query("value1")
            ) && q
            .Match(m => m
                .Field(f => f.Field7)
                .Query("value7")
            )
        )
    )
    .Search<Document>("search2", s => s
        .AllTypes()
        .Query(q => q
            .Bool(b => b
                .Must(mu => mu
                    .Match(m => m
                        .Field(f => f.Field2)
                        .Query("value2")
                    )
                )
            )
        )
    )
);

// get the search responses for one of the searches by name
var search1Responses = multiSearchResponse.GetResponse<Document>("search1");

This produces the following search

POST http://localhost:9200/my_index/_msearch 
{"index":"my_index"}
{"query":{"bool":{"must":[{"match":{"field1":{"query":"value1"}}},{"match":{"field7":{"query":"value7"}}}]}}}
{"index":"my_index"}
{"query":{"bool":{"must":[{"match":{"field2":{"query":"value2"}}}]}}}

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