본문 바로가기

공부방/Elasticsearch

elasticsearch - 질의(QueryDSL)

term: 특정 필드에 특정 값을 가져오고 싶을 때 사용.

terms: 특정 필드에 여러 값들 중 한개라도 존재하는 값을 가져고오 싶을 때 사용.

match: 특정 필드에 여러 값들을 and 또는 or 조건을 이용하고 이에 만족하는 결과들만 가져올 때 사용.

multi_match: 여러 필드에 여러 값들을 조합을 이용해서 가져오고 싶을 때 사용.

match_phrase: 일치하는 문장이 속한 결과값을 가져오고 싶을 때 사용.

 

 

0. 연습 data 받아오기

검색 실습을 하기 위해 데이터를 입력하겠다. 입력할 데이터 예제 파일은 깃허브에서 내려받았다.

https://github.com/wikibook/elasticsearch/blob/master/05.%EA%B2%80%EC%83%89/5_1_books.json

https://github.com/wikibook/elasticsearch/blob/master/05.%EA%B2%80%EC%83%89/5_2_magazines.json

https://github.com/wikibook/elasticsearch/blob/master/06.%ED%8E%98%EC%9D%B4%EC%85%8B%EA%B3%BC_%EC%96%B4%EA%B7%B8%EB%A6%AC%EA%B2%8C%EC%9D%B4%EC%85%98/6_1_hotels.json

 

접속하여 레파지토리에서 예제 파일을 다운로드받는다. 

 

먼저 엘라스틱서치의 bulk API를 이용해서 5_1_books.json, 5_2_magazines.json 파일의 내용을 엘라스틱서치에 입력한다. 

 

curl -XPOST localhost:9200/_bulk --data-binary @5_1_books.json --header 'content-type:application/json'

curl -XPOST localhost:9200/_bulk --data-binary @5_2_magazines.json --header 'content-type:application/json'

curl -XPOST localhost:9200/_bulk --data-binary @6_1_hotels.json --header 'content-type:application/json'

 

1. 쿼리


 

1.1 텀, 텀즈 쿼리

 

실습1) Books 인덱스에서 title 필드값에 Prince가 들어간 결과를 찾아보자.

* 특정 필드만 검색하는 방법 : { "query" : { "term" : { "특정필드" : "특정값"}}}

 

- 아래 쿼리를 이용하여 title = prince 인 값을 찾아 보았다.

- 검색 결과를 살펴보면 대, 소문자가 다름에도 불구하고 검색 결과가 찾아졌다.

- 오히려 대문자로 검색하면 결과가 나타나지 않는 현상이 발생하고 있다. 

- 추가적으로 확인 필요

 

curl --header 'content-type:application/json' 'localhost:9200/books/_search?pretty' -d ' {"query":{"term":{"title":"prince"}}}'

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 2.0786147,
    "hits" : [
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-MGq8IEBFUzGagAAtXEk",
        "_score" : 2.0786147,
        "_source" : {
          "title" : "The Prince and the Pauper",
          "author" : "Mark Twain",
          "category" : "Children's literature",
          "written" : "1881-08-01T10:34:00",
          "pages" : 79,
          "sell" : 112100000,
          "plot" : "Tom Canty (youngest son of a family living with the dregs of society in Offal Court) has always aspired to a better life, encouraged by the local priest (who has taught him to read and write). Loitering around the palace gates one day, he sees a prince (the Prince of Wales – Edward VI). Tom is nearly caught and beaten by the Royal Guards; however, Edward stops them and invites Tom into his palace chamber. There the two boys get to know one another, fascinated by each other's life and their uncanny resemblance. They decide to switch clothes \"temporarily\". Edward leaves in a hurry before the boys are caught at their game, snatching up an article of national importance (which the reader later learns is the Great Seal of England). Soon Prince Edward is trying to escape the brutality of Tom's abusive drunken father. Tom, posing as the prince, tries to cope with court customs and manners. His fellow nobles and palace staff think \"the prince\" has an illness which has caused memory loss and fear he will go mad. They repeatedly ask him about the missing \"Great Seal\", but he knows nothing about it; however, when Tom is asked to sit in on judgments, his common-sense observations reassure them his mind is sound."
        }
      }
    ]
  }
}

 

 

실습2) Books 인덱스에서 title 필드값에 Prince와 King이 들어간 결과를 찾아보자.

* 특정 필드만 검색하는 방법 : { "query" : { "terms" : { "특정필드" : "특정값"}}}

 

- term 대신 terms query를 이용하면 2개 이상의 값을 검색할 수 있다.

curl --header 'content-type:application/json' 'localhost:9200/books/_search?pretty' -d ' {"query":{"terms":{"title":["prince","king"]}}}'

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "9MGq8IEBFUzGagAAtXEk",
        "_score" : 1.0,
        "_source" : {
          "title" : "King Lear",
          "author" : "William Shakespeare",
          "category" : "Tragedies",
          "written" : "1603-05-01T04:36:00",
          "pages" : 88,
          "sell" : 91300000,
          "plot" : "In the first scene the Earl of Gloucester and the Earl of Kent meet and observe that King Lear has awarded equal shares of his realm to the Duke of Cornwall and the Duke of Albany (and even before this the formal division of the next scene has taken place). Then the Earl of Gloucester introduces his illegitimate son Edmund to the Earl of Kent. In the next scene, King Lear, who is elderly and wants to retire from power, decides to divide his realm among his three daughters, and declares he'll offer the largest share to the one who loves him best. The eldest, Goneril, speaks first, declaring her love for her father in fulsome terms. Moved by her flattery Lear proceeds to grant to Goneril her share as soon as she's finished her declaration, before Regan and Cordelia have a chance to speak. He then awards to Regan her share as soon as she has spoken. When it is finally the turn of his youngest daughter, Cordelia, at first she refuses to say anything (\"Nothing, my Lord\") and then declares there is nothing to compare her love to, nor words to properly express it; she speaks honestly but bluntly, which infuriates him. In his anger he disinherits Cordelia and divides her share between Regan and Goneril. Kent objects to this unfair treatment. Enraged by Kent's protests, Lear banishes him from the country. Lear summons the Duke of Burgundy and the King of France, who have both proposed marriage to Cordelia. Learning that Cordelia has been disinherited, the Duke of Burgundy withdraws his suit, but the King of France is impressed by her honesty and marries her anyway."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-MGq8IEBFUzGagAAtXEk",
        "_score" : 1.0,
        "_source" : {
          "title" : "The Prince and the Pauper",
          "author" : "Mark Twain",
          "category" : "Children's literature",
          "written" : "1881-08-01T10:34:00",
          "pages" : 79,
          "sell" : 112100000,
          "plot" : "Tom Canty (youngest son of a family living with the dregs of society in Offal Court) has always aspired to a better life, encouraged by the local priest (who has taught him to read and write). Loitering around the palace gates one day, he sees a prince (the Prince of Wales – Edward VI). Tom is nearly caught and beaten by the Royal Guards; however, Edward stops them and invites Tom into his palace chamber. There the two boys get to know one another, fascinated by each other's life and their uncanny resemblance. They decide to switch clothes \"temporarily\". Edward leaves in a hurry before the boys are caught at their game, snatching up an article of national importance (which the reader later learns is the Great Seal of England). Soon Prince Edward is trying to escape the brutality of Tom's abusive drunken father. Tom, posing as the prince, tries to cope with court customs and manners. His fellow nobles and palace staff think \"the prince\" has an illness which has caused memory loss and fear he will go mad. They repeatedly ask him about the missing \"Great Seal\", but he knows nothing about it; however, when Tom is asked to sit in on judgments, his common-sense observations reassure them his mind is sound."
        }
      }
    ]
  }
}

 

* minimum_should_match를 이용하여 몇 개 이상의 텀과 일치해야 하는지 조건을 설정할 수 있다. -> ?? terms query에서 현재는 적용이 안되는 것 같음 (추가적인 확인 필요)

 

 

 

1.2 매치, 다중 매치 (multi match) 쿼리

 

매치 쿼리에 대한 정보는 아래 URL에서 확인할 수 있다.

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html

 

실습3) Books 인덱스에서 title 필드값에 And 또는 The가 들어간 결과를 찾아보자.

* 특정 필드만 검색하는 방법 : { "query" : { "match" : { "특정필드" : "특정값"}}}

 

"title"에 "and" 또는 "the"가 들어간 12개의 결과물을 확인할 수 있다.

 

curl --header 'content-type:application/json' 'localhost:9200/books/_search?pretty' -d ' {"query":{"match":{"title": "The And"}}}'

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 12,
      "relation" : "eq"
    },
    "max_score" : 2.044576,
    "hits" : [
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-MGq8IEBFUzGagAAtXEk",
        "_score" : 2.044576,
        "_source" : {
          "title" : "The Prince and the Pauper",
          "author" : "Mark Twain",
          "category" : "Children's literature",
          "written" : "1881-08-01T10:34:00",
          "pages" : 79,
          "sell" : 112100000,
          "plot" : "Tom Canty (youngest son of a family living with the dregs of society in Offal Court) has always aspired to a better life, encouraged by the local priest (who has taught him to read and write). Loitering around the palace gates one day, he sees a prince (the Prince of Wales – Edward VI). Tom is nearly caught and beaten by the Royal Guards; however, Edward stops them and invites Tom into his palace chamber. There the two boys get to know one another, fascinated by each other's life and their uncanny resemblance. They decide to switch clothes \"temporarily\". Edward leaves in a hurry before the boys are caught at their game, snatching up an article of national importance (which the reader later learns is the Great Seal of England). Soon Prince Edward is trying to escape the brutality of Tom's abusive drunken father. Tom, posing as the prince, tries to cope with court customs and manners. His fellow nobles and palace staff think \"the prince\" has an illness which has caused memory loss and fear he will go mad. They repeatedly ask him about the missing \"Great Seal\", but he knows nothing about it; however, when Tom is asked to sit in on judgments, his common-sense observations reassure them his mind is sound."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "88Gq8IEBFUzGagAAtXEk",
        "_score" : 2.0184987,
        "_source" : {
          "title" : "Romeo and Juliet",
          "author" : "William Shakespeare",
          "category" : "Tragedies",
          "written" : "1562-12-01T20:40:00",
          "pages" : 125,
          "sell" : 182700000,
          "plot" : "Meanwhile, Benvolio talks with his cousin Romeo, Montague's son, about Romeo's recent depression. Benvolio discovers that it stems from unrequited infatuation for a girl named Rosaline, one of Capulet's nieces. Persuaded by Benvolio and Mercutio, Romeo attends the ball at the Capulet house in hopes of meeting Rosaline. However, Romeo instead meets and falls in love with Juliet. Juliet's cousin, Tybalt, is enraged at Romeo for sneaking into the ball, but is only stopped from killing Romeo by Juliet's father, who doesn't wish to shed blood in his house. After the ball, in what is now called the \"balcony scene\", Romeo sneaks into the Capulet orchard and overhears Juliet at her window vowing her love to him in spite of her family's hatred of the Montagues. Romeo makes himself known to her and they agree to be married. With the help of Friar Laurence, who hopes to reconcile the two families through their children's union, they are secretly married the next day."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "8cGq8IEBFUzGagAAtXEk",
        "_score" : 0.40767306,
        "_source" : {
          "title" : "The Tempest",
          "author" : "William Shakespeare",
          "category" : "Comedies",
          "written" : "1610-03-01T11:34:00",
          "pages" : 62,
          "sell" : 275600000,
          "plot" : "Magician Prospero, rightful Duke of Milan, and his daughter, Miranda, have been stranded for twelve years on an island after Prospero's jealous brother Antonio (aided by Alonso, the King of Naples) deposed him and set him adrift with the then-3-year-old Miranda. Gonzalo, the King's counsellor, had secretly supplied their boat with plenty of food, water, clothes and the most-prized books from Prospero's library. Possessing magic powers due to his great learning, Prospero is reluctantly served by a spirit, Ariel, whom Prospero had rescued from a tree in which he had been trapped by the witch Sycorax. Prospero maintains Ariel's loyalty by repeatedly promising to release the \"airy spirit\" from servitude. Sycorax had been banished to the island, and had died before Prospero's arrival. Her son, Caliban, a deformed monster and the only non-spiritual inhabitant before the arrival of Prospero, was initially adopted and raised by him. He taught Prospero how to survive on the island, while Prospero and Miranda taught Caliban religion and their own language. Following Caliban's attempted rape of Miranda, he had been compelled by Prospero to serve as the magician's slave. In slavery, Caliban has come to view Prospero as a usurper and has grown to resent him and his daughter. Prospero and Miranda in turn view Caliban with contempt and disgust."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "_sGq8IEBFUzGagAAtXEk",
        "_score" : 0.3644046,
        "_source" : {
          "title" : "Journey to the Center of the Earth",
          "author" : "Jules Verne",
          "category" : [
            "Science fiction",
            "adventure novel"
          ],
          "written" : "1864-07-01T11:30:00",
          "pages" : 212,
          "sell" : 42100000,
          "plot" : "Professor Lidenbrock decides to lock everyone in the house and force himself and the others (Axel, and the maid, Martha) to go without food until he cracks the code. Axel discovers the answer when fanning himself with the deciphered text: Lidenbrock's decipherment was correct, and only needs to be read backwards to reveal sentences written in rough Latin."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-sGq8IEBFUzGagAAtXEk",
        "_score" : 0.35909772,
        "_source" : {
          "title" : "The Three Musketeers",
          "author" : "Alexandre Dumas",
          "category" : "Historical novel",
          "written" : "1844-10-01T12:00:00",
          "pages" : 340,
          "sell" : 61400000,
          "plot" : "In 1625 France, d'Artagnan—a poor young nobleman—leaves his family in Gascony and travels to Paris with the intention of joining the Musketeers of the Guard. However, en route, at an inn in Meung-sur-Loire, an older man derides d'Artagnan's horse and, feeling insulted, d'Artagnan demands to fight a duel with him. The older man's companions beat d'Artagnan unconscious with a pot and a metal tong that breaks his sword. His letter of introduction to Monsieur de Tréville, the commander of the Musketeers, is stolen. D'Artagnan resolves to avenge himself upon the man, who is later revealed to be the Comte de Rochefort, an agent of Cardinal Richelieu, who is in Meung to pass orders from the Cardinal to Milady de Winter, another of his agents."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-8Gq8IEBFUzGagAAtXEk",
        "_score" : 0.35909772,
        "_source" : {
          "title" : "The Time Machine",
          "author" : "H. G. Wells",
          "category" : "Science fiction novel",
          "written" : "1895-11-01T05:01:00",
          "pages" : 227,
          "sell" : 22100000,
          "plot" : "The book's protagonist is an English scientist and gentleman inventor living in Richmond, Surrey in Victorian England, and identified by a narrator simply as the Time Traveller. The narrator recounts the Traveller's lecture to his weekly dinner guests that time is simply a fourth dimension, and his demonstration of a tabletop model machine for travelling through it. He reveals that he has built a machine capable of carrying a person, and returns at dinner the following week to recount a remarkable tale, becoming the new narrator."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "_MGq8IEBFUzGagAAtXEk",
        "_score" : 0.35909772,
        "_source" : {
          "title" : "The Invisible Man",
          "author" : "H. G. Wells",
          "category" : [
            "Horror",
            "Science fiction novel"
          ],
          "written" : "1897-05-01T07:32:00",
          "pages" : 210,
          "sell" : 67800000,
          "plot" : "A mysterious stranger, Griffin, arrives at the local inn of the English village of Iping, West Sussex, during a snowstorm. The stranger wears a long-sleeved, thick coat and gloves, his face hidden entirely by bandages except for a fake pink nose, and a wide-brimmed hat. He is excessively reclusive, irascible, and unfriendly. He demands to be left alone and spends most of his time in his rooms working with a set of chemicals and laboratory apparatus, only venturing out at night. While staying at the inn, hundreds of strange glass bottles arrive that Griffin calls his luggage. Many local townspeople believe this to be very strange. He becomes the talk of the village (one of the novel's most charming aspects is its portrayal of small-town life in southern England, which the author knew from first-hand experience)."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "8sGq8IEBFUzGagAAtXEk",
        "_score" : 0.3208657,
        "_source" : {
          "title" : "The Merchant of Venice",
          "author" : "William Shakespeare",
          "category" : "Comedies",
          "written" : "1596-02-01T04:42:00",
          "pages" : 97,
          "sell" : 124100000,
          "plot" : "Bassanio, a young Venetian of noble rank, wishes to woo the beautiful and wealthy heiress Portia of Belmont. Having squandered his estate, he needs 3,000 ducats to subsidise his expenditures as a suitor. Bassanio approaches his friend Antonio, a wealthy merchant of Venice who has previously and repeatedly bailed him out. Antonio agrees, but since he is cash-poor – his ships and merchandise are busy at sea – he promises to cover a bond if Bassanio can find a lender, so Bassanio turns to the Jewish moneylender Shylock and names Antonio as the loan's guarantor."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "98Gq8IEBFUzGagAAtXEk",
        "_score" : 0.2899913,
        "_source" : {
          "title" : "The Adventures of Tom Sawyer",
          "author" : "Mark Twain",
          "category" : "Folk",
          "written" : "1876-03-01T01:34:00",
          "pages" : 220,
          "sell" : 83200000,
          "plot" : "Tom Sawyer lives with his Aunt Polly and his half-brother, Sid. Tom dirties his clothes in a fight and is made to whitewash the fence the next day, as a punishment. He cleverly persuades his friends to trade him small treasures for the privilege of doing his work. He trades the treasures for Sunday School tickets which one normally receives for memorizing scriptures, redeeming them for a bible, much to the surprise and bewilderment of the superintendent who thought \"it was simply preposterous that this boy had warehoused two thousand sheaves of Scriptural wisdom on his premises—a dozen would strain his capacity, without a doubt.\""
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-cGq8IEBFUzGagAAtXEk",
        "_score" : 0.2899913,
        "_source" : {
          "title" : "The Count of Monte Cristo",
          "author" : "Alexandre Dumas",
          "category" : "Historical novel",
          "written" : "1844-09-01T12:24:00",
          "pages" : 435,
          "sell" : 49200000,
          "plot" : "In 1815 Edmond Dantès, a young and successful merchant sailor who has just recently been granted the succession of his erstwhile captain Leclère, returns to Marseille to marry his Catalan fiancée Mercédès. Leclère, a supporter of the exiled Napoléon I, found himself dying at sea and charged Dantès to deliver two objects: a package to Marshall Bertrand (exiled with Napoleon Bonaparte on Elba), and a letter from Elba to an unknown man in Paris. On the eve of his wedding to Mercédès, Fernand (Mercédès' cousin and a rival for her affections) is given subtle advice by Dantès' colleague Danglars (who is jealous of his rapid rise to captain), to send an anonymous note accusing Dantès of being a Bonapartist traitor. Caderousse (Dantès' cowardly and selfish neighbor) is drunk while the two conspirators set the trap for Dantès, and while he objects to the idea of hurting Dantès, he stays quiet the next day as Dantès is arrested then sentenced even though his testimony could have stopped the entire scandal from happening. Villefort, the deputy crown prosecutor in Marseille, while initially sympathetic to Dantès, destroys the letter from Elba when he discovers that it is addressed to his own father, a Bonapartist. In order to silence Dantès, he condemns him without trial to life imprisonment."
        }
      }
    ]
  }
}

 

실습3) Books 인덱스에서 title 필드값에 And 와 Pauper가  모두 들어간 결과를 찾아보자.

* 특정 필드만 검색하는 방법 : { "query" : { "match" : { "특정필드" : "특정값"}}}

 

"title"에 "and" 와 "pauper"가 모두 들어간 1개의 결과물을 확인할 수 있다.

 

curl --header 'content-type:application/json' 'localhost:9200/books/_search?pretty' -d ' {"query":{"match":{"title": {"query": "The pauper", "operator":"and"}}}}'

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 2.044576,
    "hits" : [
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-MGq8IEBFUzGagAAtXEk",
        "_score" : 2.044576,
        "_source" : {
          "title" : "The Prince and the Pauper",
          "author" : "Mark Twain",
          "category" : "Children's literature",
          "written" : "1881-08-01T10:34:00",
          "pages" : 79,
          "sell" : 112100000,
          "plot" : "Tom Canty (youngest son of a family living with the dregs of society in Offal Court) has always aspired to a better life, encouraged by the local priest (who has taught him to read and write). Loitering around the palace gates one day, he sees a prince (the Prince of Wales – Edward VI). Tom is nearly caught and beaten by the Royal Guards; however, Edward stops them and invites Tom into his palace chamber. There the two boys get to know one another, fascinated by each other's life and their uncanny resemblance. They decide to switch clothes \"temporarily\". Edward leaves in a hurry before the boys are caught at their game, snatching up an article of national importance (which the reader later learns is the Great Seal of England). Soon Prince Edward is trying to escape the brutality of Tom's abusive drunken father. Tom, posing as the prince, tries to cope with court customs and manners. His fellow nobles and palace staff think \"the prince\" has an illness which has caused memory loss and fear he will go mad. They repeatedly ask him about the missing \"Great Seal\", but he knows nothing about it; however, when Tom is asked to sit in on judgments, his common-sense observations reassure them his mind is sound."
        }
      }
    ]
  }
}

 

실습4) Books 인덱스에서 title 필드값에 And 와 Pauper가  모두 들어간 결과를 찾아보자.

* minimum_should_match 옵션을 이용하여 일치하는 개수를 지정할 수 있다.

 

- 실습 3과 동일한 결과가 나타난다.

 

 

curl --header 'content-type:application/json' 'localhost:9200/books/_search?pretty' -d ' {"query":{"match":{"title": {"query": "The pauper", "minimum_should_match":2}}}}'

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 2.4931412,
    "hits" : [
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-MGq8IEBFUzGagAAtXEk",
        "_score" : 2.4931412,
        "_source" : {
          "title" : "The Prince and the Pauper",
          "author" : "Mark Twain",
          "category" : "Children's literature",
          "written" : "1881-08-01T10:34:00",
          "pages" : 79,
          "sell" : 112100000,
          "plot" : "Tom Canty (youngest son of a family living with the dregs of society in Offal Court) has always aspired to a better life, encouraged by the local priest (who has taught him to read and write). Loitering around the palace gates one day, he sees a prince (the Prince of Wales – Edward VI). Tom is nearly caught and beaten by the Royal Guards; however, Edward stops them and invites Tom into his palace chamber. There the two boys get to know one another, fascinated by each other's life and their uncanny resemblance. They decide to switch clothes \"temporarily\". Edward leaves in a hurry before the boys are caught at their game, snatching up an article of national importance (which the reader later learns is the Great Seal of England). Soon Prince Edward is trying to escape the brutality of Tom's abusive drunken father. Tom, posing as the prince, tries to cope with court customs and manners. His fellow nobles and palace staff think \"the prince\" has an illness which has caused memory loss and fear he will go mad. They repeatedly ask him about the missing \"Great Seal\", but he knows nothing about it; however, when Tom is asked to sit in on judgments, his common-sense observations reassure them his mind is sound."
        }
      }
    ]
  }
}

 

실습4) Books 인덱스에서 title 또는 plot필드값에 prince 또는 king이 들어간 결과를 찾아보자.

 

* 다중 필드에서 다중 값을 검색하는 방법 : { "query" : { "multi_match" : { "fields" : ["특정값"], "query" : "특정 값"}}}

 

curl --header 'content-type:application/json' 'localhost:9200/books/_search?pretty' -d ' {"query":{"multi_match":{"fields": ["title", "plot"], "query":"prince king"}}}'

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 4,
      "relation" : "eq"
    },
    "max_score" : 5.8271465,
    "hits" : [
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "9cGq8IEBFUzGagAAtXEk",
        "_score" : 5.8271465,
        "_source" : {
          "title" : "Hamlet",
          "author" : "William Shakespeare",
          "category" : "Tragedies",
          "written" : "1599-06-01T12:34:00",
          "pages" : 172,
          "sell" : 146100000,
          "plot" : "The protagonist of Hamlet is Prince Hamlet of Denmark, son of the recently deceased King Hamlet, and nephew of King Claudius, his father's brother and successor. Claudius hastily married King Hamlet's widow, Gertrude, Hamlet's mother. Denmark has a long-standing feud with neighbouring Norway, and an invasion led by the Norwegian prince, Fortinbras, is expected."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "-MGq8IEBFUzGagAAtXEk",
        "_score" : 3.092677,
        "_source" : {
          "title" : "The Prince and the Pauper",
          "author" : "Mark Twain",
          "category" : "Children's literature",
          "written" : "1881-08-01T10:34:00",
          "pages" : 79,
          "sell" : 112100000,
          "plot" : "Tom Canty (youngest son of a family living with the dregs of society in Offal Court) has always aspired to a better life, encouraged by the local priest (who has taught him to read and write). Loitering around the palace gates one day, he sees a prince (the Prince of Wales – Edward VI). Tom is nearly caught and beaten by the Royal Guards; however, Edward stops them and invites Tom into his palace chamber. There the two boys get to know one another, fascinated by each other's life and their uncanny resemblance. They decide to switch clothes \"temporarily\". Edward leaves in a hurry before the boys are caught at their game, snatching up an article of national importance (which the reader later learns is the Great Seal of England). Soon Prince Edward is trying to escape the brutality of Tom's abusive drunken father. Tom, posing as the prince, tries to cope with court customs and manners. His fellow nobles and palace staff think \"the prince\" has an illness which has caused memory loss and fear he will go mad. They repeatedly ask him about the missing \"Great Seal\", but he knows nothing about it; however, when Tom is asked to sit in on judgments, his common-sense observations reassure them his mind is sound."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "9MGq8IEBFUzGagAAtXEk",
        "_score" : 2.9221406,
        "_source" : {
          "title" : "King Lear",
          "author" : "William Shakespeare",
          "category" : "Tragedies",
          "written" : "1603-05-01T04:36:00",
          "pages" : 88,
          "sell" : 91300000,
          "plot" : "In the first scene the Earl of Gloucester and the Earl of Kent meet and observe that King Lear has awarded equal shares of his realm to the Duke of Cornwall and the Duke of Albany (and even before this the formal division of the next scene has taken place). Then the Earl of Gloucester introduces his illegitimate son Edmund to the Earl of Kent. In the next scene, King Lear, who is elderly and wants to retire from power, decides to divide his realm among his three daughters, and declares he'll offer the largest share to the one who loves him best. The eldest, Goneril, speaks first, declaring her love for her father in fulsome terms. Moved by her flattery Lear proceeds to grant to Goneril her share as soon as she's finished her declaration, before Regan and Cordelia have a chance to speak. He then awards to Regan her share as soon as she has spoken. When it is finally the turn of his youngest daughter, Cordelia, at first she refuses to say anything (\"Nothing, my Lord\") and then declares there is nothing to compare her love to, nor words to properly express it; she speaks honestly but bluntly, which infuriates him. In his anger he disinherits Cordelia and divides her share between Regan and Goneril. Kent objects to this unfair treatment. Enraged by Kent's protests, Lear banishes him from the country. Lear summons the Duke of Burgundy and the King of France, who have both proposed marriage to Cordelia. Learning that Cordelia has been disinherited, the Duke of Burgundy withdraws his suit, but the King of France is impressed by her honesty and marries her anyway."
        }
      },
      {
        "_index" : "books",
        "_type" : "book",
        "_id" : "8cGq8IEBFUzGagAAtXEk",
        "_score" : 1.2353308,
        "_source" : {
          "title" : "The Tempest",
          "author" : "William Shakespeare",
          "category" : "Comedies",
          "written" : "1610-03-01T11:34:00",
          "pages" : 62,
          "sell" : 275600000,
          "plot" : "Magician Prospero, rightful Duke of Milan, and his daughter, Miranda, have been stranded for twelve years on an island after Prospero's jealous brother Antonio (aided by Alonso, the King of Naples) deposed him and set him adrift with the then-3-year-old Miranda. Gonzalo, the King's counsellor, had secretly supplied their boat with plenty of food, water, clothes and the most-prized books from Prospero's library. Possessing magic powers due to his great learning, Prospero is reluctantly served by a spirit, Ariel, whom Prospero had rescued from a tree in which he had been trapped by the witch Sycorax. Prospero maintains Ariel's loyalty by repeatedly promising to release the \"airy spirit\" from servitude. Sycorax had been banished to the island, and had died before Prospero's arrival. Her son, Caliban, a deformed monster and the only non-spiritual inhabitant before the arrival of Prospero, was initially adopted and raised by him. He taught Prospero how to survive on the island, while Prospero and Miranda taught Caliban religion and their own language. Following Caliban's attempted rape of Miranda, he had been compelled by Prospero to serve as the magician's slave. In slavery, Caliban has come to view Prospero as a usurper and has grown to resent him and his daughter. Prospero and Miranda in turn view Caliban with contempt and disgust."
        }
      }
    ]
  }
}

 

1.2 불 (bool) 쿼리

 

match 보다 더욱 세세한 사항을 설정하여 결과 값을 가져올 수 있다.

    - must : 이 쿼리에 반드시 해당해야 한다. and 조건

    - must_not: 이 쿼리에 해당해서는 안된다. not 조건

    - should: 이 쿼리에 해당될 필요는 없지만 해당된다면 더 높은 스코어를 가진다. or 조건과 유사

 

실습5) Books 인덱스에서 

    - title 필드에 the를 포함하고 (must)

    - plot 필드에 prince를 포함하지 않으며 (must_not)

    - title 필드에 time 또는 world가 있으면 더 높은 우선순위를 가지는 (should) 

    - 검색 결과를 구하라

 

 

curl --header 'content-type:application/json' 'localhost:9200/books/_search?pretty' -d ' {"query":{"bool":{"must": {"term" : {"title": "the"}}, "must_not":{"term":{"plot":"prince"}}, "should" : [{"term":{"title":"world"}},{"term":{"title":"time"}}]}}}'

 

 

 

'공부방 > Elasticsearch' 카테고리의 다른 글

test  (0) 2023.04.28
elastic search manual  (0) 2022.08.22
elastic search - 검색  (0) 2022.07.12
elasticsearch - bucket  (0) 2022.07.06
elasticsearch - metric aggregation  (0) 2022.07.06