如何从elasticsearch内存节点添加和检索结构化数据?

时间:2014-12-02 10:51:43

标签: scala elasticsearch

我正在Scala项目中尝试使用elasticsearch(1.4)API。 我最琐碎的目标是将数据添加到内存节点并在之后检索它。我正在广泛地关注documentation中给出的例子。不过,我经历了奇怪的行为。

def clusterName: String = "foo-bar"
def indexName: String = "lorem"
def typeName: String = "ipsum"

// ES Settings
var elasticsearchSettings = ImmutableSettings.settingsBuilder()
    .put("index.gateway.type", "none")
    .put("index.number_of_shards", 1)
    .put("index.number_of_replicas", 0)
    .put("path.data", "target/es-data")
    .put("index.store.type", "memory").build()

// ES Node
var node = nodeBuilder()
    .clusterName(clusterName)
    .local(true)
    .settings(elasticsearchSettings).node()

// ES Client
var client = node.client()

// Preapring ES Index
var preparation = client.prepareIndex(indexName, typeName)
    .setSource(s"""{"foo" : "bar"}""")
    .execute()
    .actionGet()

// Preparing Request
val requestBuilder = client.prepareSearch(indexName)
    .setFrom(0)
    .setSize(20)
    .setQuery(QueryBuilders.filteredQuery(null, null))

val response = requestBuilder.execute().actionGet(5000)

我的期望是此响应现在的长度为1(包含资源foo)。

运行println(response)会生成以下输出:

{
  "took" : 32,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

为什么找不到我新添加的资源?

1 个答案:

答案 0 :(得分:0)

经过一些测试后,我设法通过在准备索引后刷新分片来解决这个问题。

这是通过在client.admin().indices().prepareRefresh().execute().actionGet()之后调用client.prepareIndex来完成的。

考虑以下工作示例:

def clusterName: String = "foo-bar"
def indexName: String = "lorem"
def typeName: String = "ipsum"

// ES Settings
var elasticsearchSettings = ImmutableSettings.settingsBuilder()
    .put("index.gateway.type", "none")
    .put("index.number_of_shards", 1)
    .put("index.number_of_replicas", 0)
    .put("path.data", "target/es-data")
    .put("index.store.type", "memory").build()

// ES Node
var node = nodeBuilder()
    .clusterName(clusterName)
    .local(true)
    .settings(elasticsearchSettings).node()

// ES Client
var client = node.client()

// Preapring ES Index
var preparation = client.prepareIndex(indexName, typeName)
    .setSource(s"""{"foo" : "bar"}""")
    .execute()
    .actionGet()

// Important: Refresh the index 
client.admin().indices().prepareRefresh(indexName).execute().actionGet()

// Preparing Request
val requestBuilder = client.prepareSearch(indexName)
    .setFrom(0)
    .setSize(20)
    .setQuery(QueryBuilders.filteredQuery(null, null))

val response = requestBuilder.execute().actionGet(5000)

然后按预期返回资源{foo : "bar"}