使用Java High Level Rest Client从Elasticsearch查询数据。

huangapple 未分类评论48阅读模式
英文:

query data from elasticsearch using java highlevelrestclient

问题

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

// Assuming you have a RestHighLevelClient instance named "client"

SearchRequest searchRequest = new SearchRequest("your_index_name");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("principals.account.account_id", 1));
searchRequest.source(sourceBuilder);

SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

// Process the searchResponse as needed

Note: Make sure to replace "your_index_name" with the actual name of your Elasticsearch index. Also, ensure you have the appropriate Elasticsearch Java client library added to your project dependencies.

Please insert this code snippet into your Java program where you are interacting with Elasticsearch using the high-level REST client. This code will help you perform a search similar to the query you provided in Postman.

英文:

How to query data from elasticsearch based on the property that is present inside the actual object.

Format of data stored in elsticsearch:

{
  "principals": [
    {
      "id": 1,
      "account": {
        "account_id": 2
      }
    }
  ]
}

Search query in postman:

{
  "query": {
    "terms": {
      "account_id": [
        1
      ]
    }
  }
}

This is returning the required result in postman.

How to achieve the same in java using highlevelrestclient.

答案1

得分: 0

我不确定你上面的搜索查询是如何工作的,以获取相应的文档。

但是我通过以下方式对你的文档进行了索引和搜索:

映射:

{
  "mappings": {
    "properties": {
      "principals": {
        "properties": {
          "id": { "type": "integer" },
          "account": {
            "properties": {
              "account_id": { "type": "integer" }
            }
          }
        }
      }
    }
  }
}

搜索查询:

{
  "query": {
    "terms": {
      "principals.account.account_id": [2]
    }
  }
}

搜索结果:

"hits": [
  {
    "_index": "nestedindex",
    "_type": "_doc",
    "_id": "2",
    "_score": 1.0,
    "_source": {
      "principals": [
        {
          "id": 1,
          "account": {
            "account_id": 2
          }
        }
      ]
    }
  }
]

通过Elasticsearch RestHighLevelClient进行的搜索查询

SearchRequest searchRequest = new SearchRequest("testIndex"); //替换为你的索引名称
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); 
List<Integer> accountIds = new ArrayList<Integer>();
accountIds.add(2);
sourceBuilder.query(QueryBuilders.termsQuery("principals.account.account_id", accountIds)); 
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); 
searchRequest.source(sourceBuilder);
SearchResponse searchResponse =   
                client.search(searchRequest, RequestOptions.DEFAULT);  //client是ES客户端

return searchResponse; //你可以通过searchResponse.getHits().getHits()来读取搜索结果

在spring-boot应用程序中,可以通过在项目中创建配置文件并在需要的地方进行自动装配,实例化ElasticSearch客户端:

@Configuration
@Primary
public class ElasticsearchConfig {
	
    private RestHighLevelClient restHighLevelClient;
    
    @Bean(destroyMethod = "close")
    public RestHighLevelClient client() {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        return client;
    }
}
英文:

I am not sure how your above search query worked in fetching corresponding document.

But I had indexed and searched your document through this way :

mapping:

{
  &quot;mappings&quot;: {
    &quot;properties&quot;: { 
      
      &quot;principals&quot;: { 
        &quot;properties&quot;: {
          &quot;id&quot;:  { &quot;type&quot;: &quot;integer&quot; },
          &quot;account&quot;: { 
            &quot;properties&quot;: {
              &quot;account_id&quot;: { &quot;type&quot;: &quot;integer&quot; }
             
            }
          }
        }
      }
    }
  }
}

search query:

 {
  &quot;query&quot;: {
    &quot;terms&quot;: {
      &quot;principals.account.account_id&quot;: [2]
    }
  }
}

Search result :

&quot;hits&quot;: [
  {
    &quot;_index&quot;: &quot;nestedindex&quot;,
    &quot;_type&quot;: &quot;_doc&quot;,
    &quot;_id&quot;: &quot;2&quot;,
    &quot;_score&quot;: 1.0,
    &quot;_source&quot;: {
      &quot;principals&quot;: [
        {
          &quot;id&quot;: 1,
          &quot;account&quot;: {
            &quot;account_id&quot;: 2
          }
        }
      ]
    }
  }
]

Search query through Elasticsearch Resthighlevelclient

SearchRequest searchRequest = new SearchRequest(&quot;testIndex&quot;); //in place of &quot;testIndex&quot; you can give your index name
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); 
List&lt;Integer&gt; accountIds = new ArrayList&lt;Integer&gt;();
accountIds.add(2);
sourceBuilder.query(QueryBuilders.termsQuery(&quot;principals.account.account_id&quot;, accountIds)); 
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); 
searchRequest.source(sourceBuilder);
SearchResponse searchResponse =   
                client.search(searchRequest, RequestOptions.DEFAULT);  //client is ES client
		
return searchResponse; //you can read your hits through searchResponse.getHits().getHits()

ElasticSearch client can be instantiated in spring-boot application by creating configuration file in your project and autowiring the client where required:

@Configuration
@Primary
public class ElasticsearchConfig {
	
    private RestHighLevelClient restHighLevelClient;
    
    @Bean(destroyMethod = &quot;close&quot;)
    public RestHighLevelClient client() {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost(&quot;localhost&quot;, 9200, &quot;http&quot;)));

        return client;

    }

huangapple
  • 本文由 发表于 2020年4月10日 15:25:19
  • 转载请务必保留本文链接:https://java.coder-hub.com/61135725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定