How to write a query in Nest? - nest

I do not understand how to write a simple query like this with Nest. Can anyone help me?
{
"query" : {
"match" : {
"Level" : "INFO"
}
}
}

client.Search(s=>s
.Query(q=>
q.Match(m=>m.OnField(p=>p.Level).Query("INFO"))
)
)

var result = EsClient.Search<Business>(q => q
.Query(qq =>
{
QueryContainer termQuery = null;
if (!string.IsNullOrWhiteSpace(searchTerm))
{
var toLowSearchTerm = searchTerm.ToLower();
termQuery |= qq.QueryString(qs => qs.OnFieldsWithBoost(f => f.Add("companyName", 2.0)).Query(toLowSearchTerm));
termQuery |= qq.Term("level", toLowSearchTerm);
termQuery |= qq.Term("phone", toLowSearchTerm);
termQuery |= qq.Term("fax", toLowSearchTerm);
termQuery |= qq.Term("mobile", toLowSearchTerm);
termQuery |= qq.Term("nationalID", toLowSearchTerm);
}
}
return termQuery ;

Related

Cannot create logical device only in debug mode

I'm getting VK_ERROR_FEATURE_NOT_PRESENT(-8).
But i'm using vkGetPhysicalDeviceFeatures to get features.
My Code:
std::vector<VkDeviceQueueCreateInfo> LogicalDevice::CreateDeviceQueueCreateInfos(QueueFamilies queueFamilies)
{
std::vector uniqueQueueFamilies = queueFamilies.GetUniqueQueueFamilies();
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
for (auto queueFamily : uniqueQueueFamilies)
{
const int countOfQueues = queueFamily.CountOfQueues;
std::vector<float> queuePriorities(countOfQueues);
for (int indexOfPriority = 0; indexOfPriority < countOfQueues; indexOfPriority++)
{
queuePriorities[indexOfPriority] = 1.0f - ( (float) indexOfPriority / countOfQueues);
}
VkDeviceQueueCreateInfo queueCreateInfo{};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily.Index.value();
queueCreateInfo.queueCount = queueFamily.CountOfQueues;
queueCreateInfo.flags = queueFamily.Flags;
queueCreateInfo.pQueuePriorities = queuePriorities.data();
queueCreateInfos.push_back(queueCreateInfo);
}
return queueCreateInfos;
}
VkDeviceCreateInfo LogicalDevice::GetDeviceCreateInfo(std::vector<VkDeviceQueueCreateInfo> deviceQueueCreateInfos, VkPhysicalDevice physicalDevice)
{
VkPhysicalDeviceFeatures deviceFeatures{};
vkGetPhysicalDeviceFeatures(physicalDevice, &deviceFeatures);
VkDeviceCreateInfo deviceCreateInfo{};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(deviceQueueCreateInfos.size());
deviceCreateInfo.pQueueCreateInfos = deviceQueueCreateInfos.data();
deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
return deviceCreateInfo;
}
void LogicalDevice::Initialize(VkPhysicalDevice physicalDevice, VkSurfaceKHR surfaceForPickingPhysicalDevice)
{
m_queueFamilies = QueueFamilies::GetQueueFamilies(physicalDevice, surfaceForPickingPhysicalDevice);
std::vector<VkDeviceQueueCreateInfo> deviceQueueCreateInfos = CreateDeviceQueueCreateInfos(m_queueFamilies);
VkDeviceCreateInfo deviceCreateInfo = GetDeviceCreateInfo(deviceQueueCreateInfos, physicalDevice);
VkResult result = vkCreateDevice(physicalDevice, &deviceCreateInfo, nullptr, &m_vulkanDevice);
if (result != VK_SUCCESS)
{
throw new std::runtime_error("Cannot create logical device.");
}
}
The deviceFeature variable that you read the features into and which is pointed at in the create info structure is local to GetDeviceCreateInfo. This is out-of-scope at the point where you call vkCreateDevice, which results in undefined behavior. You're probably getting random junk at device creation time instead, which causes that error.

working with option of $query in yii2

i want use where for $query.
foreach ($oppId as $o) {
$id = $o['opportunity_id'];
$query->Where("id=$id");
}
When I use this. All items shown
$query->orWhere("id=$id");
i need get this query :
SELECT * FROM `opportunity` WHERE id =27 or id =28
this is all of my function :
public function actionShow($type = 0, $city = 0, $client = 0) {
$query = (new \yii\db\Query())->select(['*'])->from('opportunity ')->innerJoin('profile_details', 'opportunity.user_id=profile_details.user_id')->orderBy('id desc');
$query->Where('id !=-1');
if (isset($_REQUEST['type'])) {
$type = $_REQUEST['type'];
if ($type != 0) {
$query->andWhere("project_type_id=$type");
}
}
if (isset($_REQUEST['city'])) {
$city = $_REQUEST['city'];
if ($city != 0) {
$query->andWhere("state_id=$city");
}
}
if (isset($_REQUEST['client'])) {
$client = $_REQUEST['client'];
if ($client != 0) {
$oppId = \app\models\OpportunityControl::find()
->where('project_type_id = :project_type_id', [':project_type_id' => $client])
->all();
foreach ($oppId as $o) {
$id = $o['opportunity_id'];
$query->orWhere("id=$id");
}
}
}
You very much do not want to use strings to add to the query under any circumstances as that is ripe for SQL injection. I'd format it like this:
...
$params = [];
foreach ($oppId as $o) {
$params[] = $o->opportunity_id;
}
$query->andWhere(['in', 'id', $params]);
...
You should also adjust your other query params so that you are not passing variables into SQL via a string.
if (isset($_REQUEST['type'])) {
$type = $_REQUEST['type'];
if ($type != 0) {
$query->andWhere(['project_type_id' => $type]);
}
}
if (isset($_REQUEST['city'])) {
$city = $_REQUEST['city'];
if ($city != 0) {
$query->andWhere(['state_id' => $city]);
}
}
See the Yii2 guide on using variables in queries for what you are trying to avoid here. Specifically:
Do NOT embed variables directly in the condition like the following, especially if the variable values come from end user inputs, because this will make your application subject to SQL injection attacks.
// Dangerous! Do NOT do this unless you are very certain $status must be an integer.
$query->where("status=$status");
I do it with Arrays
$query->where(['or',['id'=>27],['id'=>28]]);
But in your case save all ids in a Array is not possible,I do it with string inside foreach
$StringWhere='';
$LastElement = end($oppId);
foreach ($oppId as $o)
{
$id = $o['opportunity_id'];
$StringWhere.=' id='.$id;
if($o!=$LastElement)
{
$StringWhere.=' or ';
}
}
$query->where($StringWhere);
$query->where(['or',['id'=>27],['id'=>28]]);
I use this and it works perfectly as mentioned by metola. :)

Entity Framework PredicateBuilder multiple "AND" && "OR"

I need add And && Or same query
This is my code
var predicate = PredicateBuilder.True<Summon>();
if (!string.IsNullOrEmpty(param.id))
{
predicate = predicate.And(m => m.id== param.id);
}
if (!string.IsNullOrEmpty(param.subjects))
{
var subjectsPredicate = PredicateBuilder.False<Summon>();
string[] subjects = param.subjects.Split(',');
for (int i = 0; i < subjects.Length; i++)
{
subjectsPredicate = subjectsPredicate.Or(m => m.SubjectId ==subjects[i]);
}
predicate = predicate.And(subjectsPredicate);
}
My Problem is that when the subjects exist I got an error, all other queries work good just this "sub-query" make the query to fail.
This is my error, If subjects exist.
The solution is simple - Not using the array on the search query
subjects[i] - Does not work
instead of write
for (int i = 0; i < subjects.Length; i++)
{
subjectsPredicate = subjectsPredicate.Or(m => m.SubjectId ==subjects[i]);
}
Neet to write
foreach (string key in subjects)
{
subjectsPredicate = subjectsPredicate.Or(m => m.SubjectId == key);
}

Get raw sql from Phalcon query builder

Is it possible to extract raw sql query from the query builder instance in Phalcon? Something like this?
$queryBuilder = new Phalcon\Mvc\Model\Query\Builder();
$queryBuilder
->from(…)
->where(…);
$rawSql = $queryBuilder->hypotheticalGetRawQueryMethod();
By error and trial the below seems to working. Would be great if someone could confirm if there's a better way.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…);
$intermediate = $queryBuilder->getQuery()->parse();
$dialect = DI::getDefault()->get('db')->getDialect();
$sql = $dialect->select($intermediate);
Edit: As of 2.0.3 you can do it super simple, see comment for full details:
$modelsManager->createBuilder()
->from('Some\Robots')
->getQuery()
->getSql()
you can use getRealSqlStatement() (or similar function name) on the DbAdapter. See http://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter.html
According to documentation you can get this way the resulting sql query.
Or wait, this might not work on querybuilder. Otherwise you can setup low level query logging: http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements
$db = Phalcon\DI::getDefault()->getDb();
$sql = $db->getSQLStatement();
$vars = $db->getSQLVariables();
if ($vars) {
$keys = array();
$values = array();
foreach ($vars as $placeHolder=>$var) {
// fill array of placeholders
if (is_string($placeHolder)) {
$keys[] = '/:'.ltrim($placeHolder, ':').'/';
} else {
$keys[] = '/[?]/';
}
// fill array of values
// It makes sense to use RawValue only in INSERT and UPDATE queries and only as values
// in all other cases it will be inserted as a quoted string
if ((strpos($sql, 'INSERT') === 0 || strpos($sql, 'UPDATE') === 0) && $var instanceof \Phalcon\Db\RawValue) {
$var = $var->getValue();
} elseif (is_null($var)) {
$var = 'NULL';
} elseif (is_numeric($var)) {
$var = $var;
} else {
$var = '"'.$var.'"';
}
$values[] = $var;
}
$sql = preg_replace($keys, $values, $sql, 1);
}
More you can read there
The following is the common solution:
$result = $modelsManager->createBuilder()
->from(Foo::class)
->where('slug = :bar:', ['bar' => "some-slug"])
->getQuery()
->getSql();
But you might not expect to see the query without its values, like in:
die(print_r($result, true));
Array
(
[sql] => SELECT `foo`.`id`, `foo`.`slug` FROM `foo` WHERE `foo`.`slug` = :bar
[bind] => Array
(
[bar] => some-slug
)
[bindTypes] =>
)
So, this simple code might be useful:
public static function toSql(\Phalcon\Mvc\Model\Query\BuilderInterface $builder) : string
{
$data = $builder->getQuery()->getSql();
['sql' => $sql, 'bind' => $binds, 'bindTypes' => $bindTypes] = $data;
$finalSql = $sql;
foreach ($binds as $name => $value) {
$formattedValue = $value;
if (\is_object($value)) {
$formattedValue = (string)$value;
}
if (\is_string($formattedValue)) {
$formattedValue = sprintf("'%s'", $formattedValue);
}
$finalSql = str_replace(":$name", $formattedValue, $finalSql);
}
return $finalSql;
}
If you're using query builder then like given below then getPhql function can serve the purpose as per phalcon 3.4.4 version.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…)->getQuery();
$queryBuilder->getPhql();
if (!function_exists("getParsedBuilderQuery")) {
/**
* #param \Phalcon\Mvc\Model\Query\BuilderInterface $builder
*
* #return null|string|string[]
*/
function getParsedBuilderQuery (\Phalcon\Mvc\Model\Query\BuilderInterface $builder) {
$dialect = Phalcon\Di::getDefault()->get('db')->getDialect();
$sql = $dialect->select($builder->getQuery()->parse());
foreach ($builder->getQuery()->getBindParams() as $key => $value) {
// For strings work fine. You can add other types below
$sql = preg_replace("/:?\s?($key)\s?:?/","'$value'",$sql);
}
return $sql;
}
}
Simple function that im using for debugging.

How to use ANTLR3 lexer only, without parser?

I need to use lexer only in ANTLR3, i don't need parser. How can i do it ? I use the following code (in main.c), which i found somehwere in the internet.
#include <CLexer.h>
#include <CParser.h>
int ANTLR3_CDECL
main (int argc, char *argv[])
{
pANTLR3_UINT8 fileName;
pANTLR3_INPUT_STREAM inputStream;
pCLexer cLexer;
pANTLR3_COMMON_TOKEN_STREAM tokenStream;
pCParser cParser;
// Имя входного файла по умолчанию - "input", но
// его можно задать аргументом программы
//
if (argc < 2 || argv[1] == NULL)
{
fileName = (pANTLR3_UINT8) "./input";
}
else
{
fileName = (pANTLR3_UINT8) argv[1];
}
// Открываем входной поток, связанный с этим файлом
//
inputStream = antlr3AsciiFileStreamNew(fileName);
if ( inputStream == NULL)
{
// Аварийный выход (файл не открывается)
//
fprintf(stderr, "Failed to open file %s\n", (char *) fileName);
exit(1);
}
// Создаём лексер, связанный с открытым потоком
//
cLexer = CLexerNew(inputStream);
if ( cLexer == NULL )
{
// Аварийный выход (закончилась память, лол)
//
fprintf(stderr, "Unable to create the lexer due to malloc() failure1\n");
exit(1);
}
// Получаем поток токенов из входных данных
//
tokenStream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT,
TOKENSOURCE(cLexer));
if (tokenStream == NULL)
{
// Аварийный выход (закончилась память)
//
fprintf(stderr, "Out of memory trying to allocate token stream\n");
exit(1);
}
// Создаём парсер, связанный с потоком токенов
//
cParser = CParserNew(tokenStream);
if (cParser == NULL)
{
// Аварийный выход (закончилась память, хотя, мне кажется,
// что здесь более вероятны другие причины ошибки)
//
fprintf(stderr, "Out of memory trying to allocate parser\n");
exit(ANTLR3_ERR_NOMEM);
}
// Не знаю
//
cParser->translation_unit(cParser);
// Уничтожаем созданные "объекты" в том порядке, в котором их создавали
//
cParser ->free(cParser);
cParser = NULL;
tokenStream ->free(tokenStream);
tokenStream = NULL;
cLexer ->free (cLexer);
cLexer = NULL;
inputStream ->close (inputStream);
inputStream = NULL;
return 0;
}
But looks like it uses parser too, because i'm getting tons of parsing errors in console, when i try to use it.
Use getTokens() on the tokenStream 'object' to get an ANTLR vector of the tokens. Then print the contents of the vector.
//This runs fillBuffer() which is the function that runs the lexer to completion
pANTLR3_VECTOR tList = tokenStream->getTokens(tokenStream);
pANTLR3_COMMON_TOKEN token = tList->get(tList,0);