Search code examples
elasticsearchindexingfull-text-searchelastic-stack

Create index in elasticsearch with different document types


I need to index CLIENT entity in elastic. My object CLIENT consists of few segments (JSON documents) like

COMMON (firstname, lastname etc),
EDUCATION (fields...),
JOB (fields...) and so on. 

So my index has to store all these segments (JSON documents). I want to search by different combinations of fields and segments like: search word "university" in COMMON.firstname, COMMON.lastname, EDUCATION.field1, EDUCATION.field2 and return the search results as a list of CLIENTs with all segments.


Solution

  • I would say, that a document can look like this

    {
      ...common properties,
      "education": {
        ...education properties
      },
      "job": {
        ...job properties
      }
    }
    

    In order to index such document you can execute next query ( a new index, if does not already exist, will be created automatically )

    PUT /client/doc/1
    {
      "firstName": "...",
      "lastName": "...",
      ...other common properties,
      "education": {
        ...education properties
      },
      "job": {
        ...job properties
      }
    }
    

    Where client is the index name, doc is the type and 1 is the id of the new document.

    And then you can get a list of clients (10 by default) by executing

    GET /client/doc/_search
    

    In order to search you can execute (this will also return max 10 docs as 10 is the default)

    GET /client/doc/_search
    {
      "query": {
        "query_string" : {
          "query" : "firstName:university OR lastName:university OR education.field1:university OR education.field1:university",
          "default_field" : "content"
        }
      }
    }
    

    If you would like to explicitly specify data types for all or some of the properties please take a look at dynamic mapping. Otherwise the default data types will be assigned based on the values, like "text" for string values and etc.