Wednesday, October 19, 2016

Index documents and search them in Elasticsearch

To index documents and search them in Elasticsearch, do as follows:

curl -XDELETE localhost:9200/persons?pretty=true

curl -XPUT localhost:9200/persons?pretty=true -d '
{
  "mappings": {
    "persons": {
      "properties": {
        "firstName": {
          "type":  "string"
        },
        "lastName": {
          "type":  "string",
          "index": "not_analyzed"
        }
      }
    }
  }
}'

curl -XPOST localhost:9200/persons/persons?pretty -d '{firstName: "Johnny", lastName: "Lim", age: 20}'
curl -XPOST localhost:9200/persons/persons?pretty -d '{firstName: "John", lastName: "Kim", age: 30}'

curl localhost:9200/persons/persons/_search?pretty=true -d '{query: {match_all: {}}}'
curl localhost:9200/persons/persons/_search?pretty=true -d '{query: {term: {firstName: "Johnny"}}}'
curl localhost:9200/persons/persons/_search?pretty=true -d '{query: {term: {lastName: "Lim"}}}'
curl localhost:9200/persons/persons/_search?pretty=true -d '{query: {term: {age: 20}}}'
curl localhost:9200/persons/persons/_search?pretty=true -d '{query: {match: {firstName: "Johnny"}}}'

Note that term query with analyzed string doesn't work.

For analyzed string, use match query.

No comments:

Post a Comment